Python 记录器不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21105753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Logger not working
提问by James King
I try to use logging in Python to write some log, but strangely, only the errorwill be logged, the infowill be ignored no matter whichn level I set.
我尝试使用 Python 中的日志记录来写一些日志,但奇怪的error是,info无论我设置哪个级别,都只会记录 ,将被忽略。
code:
代码:
import logging
import logging.handlers
if __name__ == "__main__":
logger = logging.getLogger()
fh = logging.handlers.RotatingFileHandler('./logtest.log', maxBytes=10240, backupCount=5)
fh.setLevel(logging.DEBUG)#no matter what level I set here
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.info('INFO')
logger.error('ERROR')
The result is:
结果是:
2014-01-14 11:47:38,990 - root - ERROR - ERROR
According to http://docs.python.org/2/library/logging.html#logging-levels
根据http://docs.python.org/2/library/logging.html#logging-levels
The INFOshould be logged too.
也INFO应该记录。
采纳答案by abarnert
The problem is that the logger'slevel is still set to the default. So the logger discards the message before it even gets to the handlers. The fact that the handler would have accepted the message if it received it doesn't matter, because it never receives it.
问题是记录器的级别仍然设置为默认值。因此,记录器甚至在消息到达处理程序之前就将其丢弃。如果处理程序接收到消息,它会接受消息这一事实并不重要,因为它从未收到消息。
So, just add this:
所以,只需添加这个:
logger.setLevel(logging.INFO)
As the docsexplain, the logger's default level is NOTSET, which means it checks with its parent, which is the root, which has a default of WARNING.
正如文档所解释的,记录器的默认级别是NOTSET,这意味着它会检查其父级,即根,其默认值为WARNING。
And you can probably leave the handler at its default of NOTSET, which means it defers to the logger's filtering.
并且您可以将处理程序保留在其默认值NOTSET,这意味着它遵循记录器的过滤。
回答by james emanon
I think you might have to set the correct threshold.
我认为您可能必须设置正确的阈值。
logger.setLevel(logging.INFO)

