推荐两篇比较清晰的博客:
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.')