具有回调功能的Python记录器 [英] Python logger with a callback function

查看:42
本文介绍了具有回调功能的Python记录器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以配置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

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:

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