简体   繁体   English

即使设置了级别,Python 日志记录模块也不记录信息

[英]Python logging module not logging info even after level is set

I'm trying to do some basic logging.我正在尝试做一些基本的日志记录。 I'm doing the following:我正在做以下事情:

log = logging.getLogger('test')

log.error('test') # 'test' gets logged

log.info('test') # Nothing gets logged, as expected

log.setLevel(logging.INFO) # Now info should be logged, right?

log.info('test') # No output

log.setLevel(logging.INFO) # Getting desperate

log.info('test') # Still nothing

What aspect of the logging module am I missing?我缺少日志记录模块的哪些方面?

You have forgot to add handlers ie logging.basicConfig() , can you check if following code works for you.您忘记添加处理程序,即logging.basicConfig() ,您可以检查以下代码是否适合您。

import logging
logging.basicConfig()
log = logging.getLogger('test')
log.setLevel(logging.INFO)
log.error('test')
log.info('test')

You need to configure logging before you use it like below.在使用它之前,您需要配置日志记录,如下所示。 You can configure it beautifully in python.你可以用python漂亮地配置它。

logging.basicConfig(format='%(asctime)s %(name)25s %(lineno)4d %(levelname)8s: %(message)s', level=40)

above statement will print timestamp, name of the file, line number, level type, message以上语句将打印时间戳、文件名、行号、级别类型、消息

level of logging also can be set during basic Config itself (40 = ERROR)日志级别也可以在基本配置本身期间设置(40 = ERROR)

It is not necessary to call basicConfig .没有必要调用basicConfig

However, the issue is about handlers (as pointed out by @Mahesh Karia).但是,问题在于处理程序(正如@Mahesh Karia 指出的那样)。

You see, if you don't define some handlers you are dependent on whatever is already "in place" for you and that raises lots of confusion.你看,如果你不定义一些处理程序,你就依赖于已经为你“准备好”的任何东西,这会引起很多混乱。

Check this:检查这个:

You create your "test" logger你创建你的“测试”记录器

>>> log = logging.getLogger('test')

which prints WARNING messages but does not print INFO messages even after setting the level to INFO:即使将级别设置为 INFO,它也会打印 WARNING 消息但不打印 INFO 消息:

>>> log.warning('hi')
hi
>>> log.setLevel(logging.INFO)
>>> log.info('hi')
>>> 

(personally, I think this is very wrong behaviour) (就个人而言,我认为这是非常错误的行为)

It can be "solved" by manipulating "handlers".它可以通过操纵“处理程序”来“解决”。

Your "test" logger has none你的“测试”记录器没有

>>> log.handlers
[]

nor does it parent, the "root logger"它也不是父级,“根记录器”

>>> log.parent
<RootLogger root (WARNING)>
>>> log.parent.handlers
[]

however, one can add a handler easy enough (to the root logger)然而,可以很容易地添加一个处理程序(到根记录器)

>>> log.parent.addHandler(logging.StreamHandler())

and now your "test" logger "works":现在你的“测试”记录器“有效”:

>>> log.info('hi')
hi

PS.附注。 Was using Python 3.8.2 prompt after importing logging module.导入logging模块后使用 Python 3.8.2 提示。

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

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