简体   繁体   English

将自定义处理程序添加到没有记录器实例的Python记录模块中?

[英]Adding custom handler to Python logging module without a logger instance?

This is a follow-up question to the answer How to get non-blocking/real-time behavior from Python logging module? 这是答案的后续问题, 如何从Python日志记录模块获取非阻塞/实时行为? (output to PyQt QTextBrowser) provided by X.Jacobs . (输出到PyQt QTextBrowser)X.Jacobs提供。

In the Python logging module, the normal method of adding a custom handler is to define a handler class that inherits from logging.Handler (we'll call this CustomLogHandler ). 在Python日志记录模块中,添加自定义处理程序的通常方法是定义一个从logging.Handler继承的处理程序类(我们将其称为CustomLogHandler )。 To attach it to logging process, we typically do this: 要将其附加到logging过程中,通常需要执行以下操作:

import logging

class CustomLogHandler(logging.Handler):
    ... (some code here)...

logger = logging.getLogger()
logger.addHandler(CustomLogHandler)

where addHandler is a method of the logger instance. 其中addHandlerlogger实例的方法。

Question : Suppose we didn't want to get a logger (ie we don't want to do the above). :假设我们希望得到一个logger (即我们不想做以上)。 Is is possible to attach the CustomLogHandler to logging itself? 是否可以将CustomLogHandler附加到logging本身?

See comments in How to get non-blocking/real-time behavior from Python logging module? 请参阅“ 如何从Python日志记录模块获取非阻塞/实时行为”中的评论? (output to PyQt QTextBrowser) for context. (输出到PyQt QTextBrowser)作为上下文。

The premise is that it is possible to use custom handlers without any reference to the logger instance. 前提是可以使用自定义处理程序,而无需引用logger实例。

logging.getLogger() returns the root logger instance, there is no further 'up' from that object, and there is nothing else to attach a handler to beyond the root. logging.getLogger()返回根记录器实例,该对象没有进一步的“启动”,并且没有其他东西可以将处理程序附加根之外。

The module-level functions like logging.error() use the root logger; 诸如logging.error()类的模块级功能使用root logger。 quoting from the documentation : 引用文档

logging.error(msg[, *args[, **kwargs]])
Logs a message with level ERROR on the root logger. 在根记录器上记录错误级别为ERROR的消息。 The arguments are interpreted as for debug(). 参数解释为debug()。

In other words, functions like logging.error() simply call getLogger().error() . 换句话说, logging.error()类的函数只需调用getLogger().error()

Attaching your CustomLogHandler to the root logger is the correct way to add it to the module. CustomLogHandler附加到根记录器是将其添加到模块的正确方法。

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

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