我在这里有点不知所措。我可以发誓我上周早些时候有这个工作。今天我回到了它,似乎无法登录工作。
在下面的示例脚本中,我希望能够相对完整地展示我的问题。
test.py
import logging
logger = logging.getLogger()
print("Logger currently at level '{0}'".format(logger.getEffectiveLevel()))
logger.warning("Testing Warning")
logger.setLevel(60)
print("Logger currently at level '{0}'".format(logger.getEffectiveLevel()))
logger.error("Testing Error")
logger.setLevel(50)
print("Logger currently at level '{0}'".format(logger.getEffectiveLevel()))
logger.error("Testing Error")
logger.setLevel(40)
print("Logger currently at level '{0}'".format(logger.getEffectiveLevel()))
logger.error("Testing Error")
logger.setLevel(30)
print("Logger currently at level '{0}'".format(logger.getEffectiveLevel()))
logger.info("Testing Info")
logger.setLevel(20)
print("Logger currently at level '{0}'".format(logger.getEffectiveLevel()))
logger.info("Testing Info")
logger.setLevel(10)
print("Logger currently at level '{0}'".format(logger.getEffectiveLevel()))
logger.info("Testing Info")
logger.setLevel(0)
print("Logger currently at level '{0}'".format(logger.getEffectiveLevel()))
logger.info("Testing Info")
输出
Logger currently at level '30'
Testing Warning
Logger currently at level '60'
Logger currently at level '50'
Logger currently at level '40'
Testing Error
Logger currently at level '30'
Logger currently at level '20'
Logger currently at level '10'
Logger currently at level '0'
我不知道为什么日志记录模块的行为不同,考虑到我使用this官方文档尝试实现它。你可以看到它到底是如何公然忽略logger
的等级。我是否以某种方式绕过logger
而不是默认登录?我不明白。
谢谢!
答案 0 :(得分:2)
您忘记在记录器中添加处理程序。在Python 3.3(及更高版本)中,如果未指定处理程序,则使用内部"handler of last resort",其级别为WARNING
。因此,即使您的消息是通过记录器发送的,它们也会被内部处理程序丢弃(这只是为了捕获错误配置)。在Python 2.x上,您可以在stderr
- No handlers could be found for logger "root"
打印一次性消息。
如果添加一行
logger.addHandler(logging.StreamHandler())
在第一次打印之前,你会得到这样的行为:
Logger currently at level '30'
Testing Warning
Logger currently at level '60'
Logger currently at level '50'
Logger currently at level '40'
Testing Error
Logger currently at level '30'
Logger currently at level '20'
Testing Info
Logger currently at level '10'
Testing Info
Logger currently at level '0'
Testing Info
更新:无需“手动添加处理程序” - 这只是说明问题所在的最简单方法。您可以使用basicConfig()
简单地配置日志记录(控制台或文件,有限选项)或使用dictConfig()
更灵活地配置。这些方法在Python 2.7和3.2(及更高版本)中以相同的方式工作。