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....