设置日志记录级别 [英] Set logging levels

查看:121
本文介绍了设置日志记录级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用标准库来调试我的代码:

I'm trying to use the standard library to debug my code:

这很好:

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info('message')

我无法在较低级别的记录器上工作:

I can't make work the logger for the lower levels:

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.info('message')

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug('message')

我都没有得到任何回应.

I don't get any response for neither of those.

推荐答案

什么Python版本?在3.4中对我有用.但请注意, basicConfig()不会影响根处理程序如果已经设置:

What Python version? That workd for me in 3.4. But note that basicConfig() won't affect the root handler if it's already setup:

如果根记录器已经为其配置了处理程序,则此功能将不执行任何操作.

This function does nothing if the root logger already has handlers configured for it.

要显式设置根级别,请执行logging.getLogger().setLevel(logging.DEBUG).但是请确保您已经事先调用了basicConfig(),以便根记录器最初具有一些设置.即:

To set the level on root explicitly do logging.getLogger().setLevel(logging.DEBUG). But ensure you've called basicConfig() before hand so the root logger initially has some setup. I.e.:

import logging
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger('foo').debug('bah')
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('foo').debug('bah')

还请注意,记录器"及其处理程序"都具有不同的独立日志级别.因此,如果您之前已经在Python脚本中显式加载了一些复杂的记录器配置,并且与根记录器的处理程序发生了混乱,那么这可能会产生影响,并且仅使用logging.getLogger().setLevel(..)更改记录器日志级别可能不会起作用工作.这是因为附加的处理程序可能具有独立设置的日志级别.不太可能是这种情况,不是您通常不必担心的事情.

Also note that "Loggers" and their "Handlers" both have distinct independent log levels. So if you've previously explicitly loaded some complex logger config in you Python script, and that has messed with the root logger's handler(s), then this can have an effect, and just changing the loggers log level with logging.getLogger().setLevel(..) may not work. This is because the attached handler may have a log level set independently. This is unlikely to be the case and not something you'd normally have to worry about.

这篇关于设置日志记录级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆