简体   繁体   English

使用非root记录器获取所有级别的事件

[英]Getting events of all levels using a non-root logger

I have a non-root logger with some handlers attached, and I want the logger to pass every event to them, including events on user-defined levels - thus I did a log.setLevel(NOTSET) , which is the lowest level ( 0 ) . 我有一个非root记录器并附加了一些处理程序,我希望记录器将每个事件传递给他们,包括用户定义级别的事件-因此,我做了一个log.setLevel(NOTSET)它是最低级别( 0

That, however, makes the logger inherit the level of the parent (root) logger , which I don't want, since delivering those events to my handlers should be unconditional. 但是,这使记录器继承了我不需要的父(根)记录器的级别 ,因为将这些事件传递给我的处理程序应该是无条件的。

I'm wondering if log.setLevel(1) would be the right choice here. 我想知道log.setLevel(1)在这里是否是正确的选择。 It doesn't seem elegant, so maybe there's another way of accomplishing this? 它似乎并不优雅,所以也许还有另一种方法可以做到这一点?

Here's a minimal example - it prints nothing, which is not what I want: 这是一个最小的示例-它不打印任何内容,这不是我想要的:

from logging import getLogger, StreamHandler, NOTSET
from sys import stdout

log= getLogger("mylogger")
handler= StreamHandler(stdout)
log.addHandler(handler)
log.setLevel(NOTSET)

log.debug("something")

I think you're doing it the correct way: If you were only worried about handling built-in levels, you would use log.setLevel(logging.DEBUG) without a second thought. 我认为您正在以正确的方式进行操作:如果您只担心处理内置级别,则可以使用log.setLevel(logging.DEBUG) In this case you want to cover every possible user-defined level, which can be achieved using a level of 1. I don't think this is inelegant, the only difference between this and log.setLevel(logging.DEBUG) is there's no built-in constant for the level you're using. 在这种情况下,您希望涵盖每个可能的用户定义级别,可以使用级别1来实现。我认为这并不优雅,它与log.setLevel(logging.DEBUG)之间的唯一区别是没有所使用级别的内置常量。 If it makes you feel better, you could define a constant that maps to 1 to clarify what you're doing: 如果让您感觉更好,则可以定义一个映射为1的常数以阐明您的工作方式:

from logging import getLogger, StreamHandler
from sys import stdout

ALL_LEVELS = 1

log= getLogger("mylogger")
handler= StreamHandler(stdout)
log.addHandler(handler)
log.setLevel(ALL_LEVELS)

log.debug("something")

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

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