自定義日誌函數

進行了自定義日誌模塊 ,可以直接進行定義名稱,必須要有個日誌文件爲logs,生成的日誌文件 (eg:filename_20200102_info.log)

class MyLog():
    # 自定義日誌記錄
    def __init__(self, filename,):
        self.filename = filename

    def __logPath(self):
        # 日誌文件必須爲logs文件名
        return os.path.join(BASE_DIR, "logs")

    def __infoFilePath(self):
        # 文件名按天進行分類
        return f"{self.filename}_{time.strftime('%Y%m%d', time.localtime(time.time()))}_info.log"

    def __errorFilePath(self):
        return f"{self.filename}_{time.strftime('%Y%m%d', time.localtime(time.time()))}_error.log"

    def __warningFilePath(self):
        return f"{self.filename}_{time.strftime('%Y%m%d', time.localtime(time.time()))}_warning.log"

    def __logContent(self, content):
        rq = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        return "[%s ]: %s"%(rq, content)

    def __wirteFile(self, path, content):
        # 寫入
        log_content = self.__logContent(content)
        with open(path, "a", errors="ignore", encoding='utf-8') as logw:
            logw.write(log_content+"\n")
        return True

  
    def info(self, content):
        abs_path = os.path.join(self.__logPath(), self.__infoFilePath())
        self.__wirteFile(abs_path, content)
        return True

    def error(self, content):
        abs_path = os.path.join(self.__logPath(), self.__errorFilePath())
        self.__wirteFile(abs_path, content)
        return True


    def warning(self, content):
        abs_path = os.path.join(self.__logPath(), self.__warningFilePath())
        self.__wirteFile(abs_path, content)
        return True

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章