问题描述
有没有一种方法可以配置python记录器以调用自定义函数,并在每次记录时将记录消息传递给它?谢谢!
is there a way to configure a python logger to call a custom function and pass it the logging message whenever it loggs?Thanks!
推荐答案
Subclass logging.Handler
并实现 emit
方法:
Subclass logging.Handler
and implement the emit
method:
import logging
class MyHandler(logging.Handler):
def emit(self, record):
print('custom handler called with\n ', record)
logger = logging.getLogger(__name__)
logger.addHandler(MyHandler()) # or: logger.handlers = [MyHandler()]
logger.warning('Log 1')
logger.warning('Log 2')
custom handler called with
<LogRecord: __main__, 30, /home/jan/Dropbox/py/so_logging.py, 9, "Log 1">
custom handler called with
<LogRecord: __main__, 30, /home/jan/Dropbox/py/so_logging.py, 10, "Log 2">
正在记录的特定消息可以通过 record.msg
(未格式化的字符串)或 self.format(record)
(格式化的字符串,如果您添加了时间戳记)进行访问或日志级别)
The specific message being logged can be accessed as record.msg
(unformatted string) or self.format(record)
(formatted string, in case you added a timestamp or loglevel)
另外:如果还重写 logging.Handler
的 __ init __
方法,则在子类中对其进行超级调用很重要.
Additionally: If you also override the logging.Handler
's __init__
method, it is important to do the super call to it in the subclass.
logging
模块的标准警告适用于
Standard caveats for the logging
module apply:
- 默认日志级别为WARNING(因此不会传递DEBUG/INFO以发出信号)
- 将日志记录传递给记录器的所有处理程序
- 此后,它通过传递给其祖先.递归地记录层次结构
这篇关于具有回调功能的Python记录器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!