使用logging來記錄日志
import logging
log1 = logging.getLogger('MAN01')
log1.setLevel(logging.DEBUG) # 級別必須低於或等於handler的最低級別
fmt1 = logging.Formatter(
'%(asctime)s [%(levelname)-8s] (%(name)s): %(msg)s', # 輸出格式
datefmt='%Y/%m/%d %H:%M:%S' # 日期格式
)
# 定義文件輸出
fh_a = logging.FileHandler('log/log_a.log', encoding='utf-8')
fh_a.setLevel(logging.INFO) # 從info開始記錄
fh_a.setFormatter(fmt1)
log1.addHandler(fh_a)
# 定義控制台輸出
sh_a = logging.StreamHandler()
sh_a.setLevel(logging.DEBUG) # 從debug開始記錄
sh_a.setFormatter(fmt1)
log1.addHandler(sh_a)
log1.debug('Only for test')
log1.info('I\'m running')
log1.warning("I\'m done.")
控制台輸出:
2021/05/14 15:49:03 [DEBUG ] (MAN01): Only for test
2021/05/14 15:49:03 [INFO ] (MAN01): I'm running
2021/05/14 15:49:03 [WARNING ] (MAN01): I'm done.
文件輸出結果:
2021/05/14 15:49:03 [INFO ] (MAN01): I'm running
2021/05/14 15:49:03 [WARNING ] (MAN01): I'm done.
附錄: