原文链接
简单实用
import logging logger = logging.getLogger("test") # 创建实例 logger.setLevel(logging.INFO) # 设置记录级别 ch = logging.StreamHandler() # 控制台输出 ch.setLevel(logging.INFO) fh = logging.FileHandler('test.log') # 记录文件 fh.setLevel(logging.INFO) # 格式化输出 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 设置格式 ch.setFormatter(formatter) fh.setFormatter(formatter) # 添加到logger中 logger.addHandler(ch) logger.addHandler(fh) # 输出不同级别的log logger.info('this is information') logger.error('this is error message') logger.fatal('this is fatal message, it is same as logger.critical') logger.critical('this is critical message')