推薦兩篇比較清晰的部落格:
https://zhuanlan.zhihu.com/p/56968001
https://www.jianshu.com/p/feb86c06c4f4
簡單來說,即:
1、怎麼有選擇性的輸出資訊
2、怎麼有選擇性的記錄資訊
簡單、常見用法
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)
# Formatter
fmt = "%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s" # 設定log文本形式
datefmt = "%a %d %b %Y %H:%M:%S" # 設定時間
formatter = logging.Formatter(fmt, datefmt) # 建立日志formatter
# FileHandler
file_handler = logging.FileHandler('result.log')
file_handler.setFormatter(formatter)
file_handler.setLevel('DEBUG')
logger.addHandler(file_handler) # 添加到logger中
# StreamHandler
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
stream_handler.setLevel('INFO')
logger.addHandler(stream_handler) # 添加到 logger中
# Log
logger.info('Start')
logger.warning('Something maybe fail.')