我正在使用 Python 的标准日志记录系统来记录我的应用程序。我想将所有类型的消息(通过关键调试)打印到控制台,但我还想在消息级别为错误或更高级别时发送电子邮件。我一直在阅读有关日志记录的文档,但它有点令人困惑。我设置了以下测试,但它似乎无法正常工作:
import logging
log = logging.getLogger('my_test_log')
sublog = logging.getLogger('my_test_log.sublog')
log.setLevel(logging.ERROR)
log.addHandler(logging.StreamHandler())
sublog.addHandler(logging.StreamHandler())
sublog.setLevel(logging.DEBUG)
sublog.debug('This is a debug message')
sublog.info('This is an info message')
sublog.warn('This is a warn message')
sublog.error('This is an error message')
sublog.critical('This is a critical message')
注意:我现在将两个日志都设置到 StreamHandler,因为我还不想发送垃圾邮件,但在这种情况下,从技术上讲,它应该只打印错误和关键消息两次,而不是将其发送到电子邮件。完成后我会将其更改为 SMTP 以通过电子邮件将其发送出去
这是我运行这段代码时的输出:
This is a debug message
This is a debug message
This is an info message
This is an info message
This is a warn message
This is a warn message
This is an error message
This is an error message
This is a critical message
This is a critical message
基本上所有内容都会打印两次,而不仅仅是错误和关键消息。我在这里做错了什么?谢谢!
最佳答案
经过一些快速研究,Handler 对象似乎不会自动使用其父 Logger 的日志级别。你必须 set the level yourself .
import logging
log = logging.getLogger('my_test_log')
sublog = logging.getLogger('my_test_log.sublog')
log.setLevel(logging.ERROR)
handler = logging.StreamHandler()
handler.setLevel(logging.ERROR)
log.addHandler(handler)
...
关于python - 设置 python 日志记录时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12608716/