自定义日志记录的实现

2024-09-30 10:30:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图实现自定义处理程序。自定义处理程序的目的是向日志消息添加额外字段,并使多行错误消息成为一行。这就是我到目前为止的想法:

class CustomStreamHandler(logging.StreamHandler):
    def __init__(self):
        logging.StreamHandler.__init__(self)
        self.formatter = '%(asctime)s %(levelname)s %(name)s %(message)s'\
            '\tcustomfiel_id=%(customfiel_id)s'\
            '\tcustomfiel_name=%(customfiel_name)s'

    def format(self, record):
        if record.exc_info:
            record.msg += repr(super().formatException(record.exc_info))
            record.exc_info = None
        result = super().format(record)
        return result

    def emit(self, record):
        pass

format方法将多行日志转换为一行。但是我被卡住了。如何将自定义字段添加到使用此处理程序的所有日志中。顺便说一句,目前它没有发挥应有的作用。我该如何继续


Tags: nameselfinfoidformat消息处理程序init

热门问题