简体   繁体   English

设置python日志记录时出错

[英]trouble setting up python logging

I am using python's standard logging system to log my application. 我正在使用python的标准日志记录系统来记录我的应用程序。 I want to print all types of messages (debug through critical) to the console, but I also want to send an email if the message level is error or higher. 我想打印所有类型的消息(通过关键调试)到控制台,但如果消息级别错误或更高,我也想发送电子邮件。 I've been reading about the logging documentation, but it was a bit confusing. 我一直在阅读有关日志记录的文档,但它有点令人困惑。 I set up the following test, but it doesn't seem to work correctly: 我设置了以下测试,但它似乎无法正常工作:

 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')

NOTE: I set up both logs to StreamHandler right now because I don't want to spam email yet, but it should technically just print the error and critical message twice instead of sending it to email in this situation. 注意:我现在将两个日志都设置为StreamHandler,因为我还不想发送垃圾邮件,但从技术上讲,它应该只打印错误和关键消息两次,而不是在这种情况下将其发送到电子邮件。 I will change this to SMTP after this works to email it off 我将在此工作后将其更改为SMTP以通过电子邮件发送

This is my output when I run this code: 这是我运行此代码时的输出:

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

Basically everything gets printed twice rather than just the error and critical messages. 基本上所有内容都打印两次,而不仅仅是错误和关键消息。 What am I doing wrong here? 我在这做错了什么? Thanks! 谢谢!

After some quick research, it seems that Handler objects don't automatically use their parent Logger's log level. 经过一些快速研究后,似乎Handler对象不会自动使用其父Logger的日志级别。 You'll have to 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)

...

Your problem is that you have the level set to DEBUG on the sublog. 您的问题是您在子日志上将级别设置为DEBUG。 So, you will get all of the messages (just change to ERROR). 因此,您将获得所有消息(只需更改为ERROR)。 Also, there is a problem with logger.propagate being True. 此外,logger.propagate为True存在问题。

This should fix it: 这应该解决它:

sublog.propagate = False

This will stop the duplicate messages. 这将停止重复的消息。

Review the documentation about logging here . 查看有关此处记录的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM