[Python] 快速使用Logging的範例


Python logging看起來很簡單,但是其實他的設定還蠻多的,以下提供一個快速可以套用的Log class給大家參考,我把它寫一個sigleton的Class,原因是一般開發程式會有很多個檔案,我希望在同一個地方把logging設定好,其他地方只要呼叫Log.Info('Hello')就可以輕易地使用。


import logging
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path


class Log:
    _instance = None
    def __new__(cls, *args, **kw):
        if not cls._instance:
            cls._instance = super(Log, cls).__new__(cls, *args, **kw)
        return cls._instance

    def __init__(self):
        self.logger = logging.getLogger("Log")
        self.logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s : %(message)s')
        log_path = 'logs/'
        Path(log_path).mkdir(parents=True, exist_ok=True)
        handler = TimedRotatingFileHandler(log_path 
                  + 'example.log', when='d', backupCount=10)
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        #self.logger.addHandler(logging.StreamHandler())
    

    @staticmethod
    def Debug(message):
        Log().logger.debug(message)

    @staticmethod
    def Info(message):
        Log().logger.info(message)

    @staticmethod
    def Warning(message):
        Log().logger.warning(message)

    @staticmethod
    def Error(message):
        Log().logger.error(message)

    @staticmethod
    def Critical(message):
        Log().logger.critical(message)

logging的使用方法跟設定,網路上有很多詳細的說明,大家可以參考:
https://www.jianshu.com/p/cad8a77762b3
https://www.blog.pythonlibrary.org/2014/02/11/python-how-to-create-rotating-logs/
http://zwindr.blogspot.com/2016/08/python-logging.html



個人覺得要注意的地方是
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
設定了basicConfig,執行的時候卻沒有效果出現,那可能是跟其他module也有使用logging衝突到了,所以建議大家設定在你建立的logger或handler,如範例中的
self.logger.setLevel(logging.DEBUG)
handler.setFormatter(formatter)

留言

這個網誌中的熱門文章

[Python] 使用 Pyinstaller打包成執行檔

[Python] Websocket Example

[Linux] SSH筆記