[python] logging 模块 (解决控制台多重输入的问题)

[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紧急情况,系统不可用(例如系统崩溃),一般会通知所有用户
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值