[python] logging 模块
logging 模块用于便捷地输出程序日志,包括输出到控制台和文件
bug
在采用**getLogger()**方法时, logging模块会自动添加一个默认的输出到控制台的logger, 导致当添加多个logger时控制台重复输出内容, 如下:
thread 3 match num : 241
INFO:root:thread 6 match num : 242
thread 6 match num : 242
INFO:root:thread 2 match num : 243
thread 2 match num : 243
INFO:root:thread 1 match num : 244
thread 1 match num : 244
INFO:root:thread 5 match num : 245
thread 5 match num : 245
INFO:root:thread 4 match num : 246
thread 4 match num : 246
INFO:root:thread 6 match num : 247
thread 6 match num : 247
INFO:root:thread 3 match num : 248
解决方案: 添加logger前清除默认logger
logger.handlers = []
例子
import logging
# logging module
logger = logging.getLogger()
# clear default handlers for avioding the mutiple output infos
logger.handlers = []
# logger.setLevel(logging.INFO) # Log等级总开关
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
## log to file
fh = logging.FileHandler(logoutfilename+'.log')
fh.setFormatter(formatter)
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
# log to console
ch = logging.StreamHandler()
ch.setLevel(logging.INFO) # 输出到console的log等级的开关
logger.addHandler(ch)
输出等级
级别 | 信息 |
---|---|
DEBUG | 详细的debug信息; |
INFO | 证明事情按预期工作; 关键事件 |
WARNING | 虽然正常工作,但可能会出现意外,或将来可能出现问题 |
ERROR | 出现错误情况 |
CRITICAL | 严重错误,不能继续运行 |
NOTICE | 不是错误,但是可能需要处理;普通但是重要的事件; |
ALERT | 需要立即修复 |
EMERGENCY | 紧急情况,系统不可用(例如系统崩溃),一般会通知所有用户 |