繁体   English   中英

Python 修改日志消息信息?

[英]Python modifying logging message info?

我有一个日志处理程序,将警告消息记录到列表中。 但是我的脚本的构造方式,消息的记录行号将被抵消。 所以我想用我自己的行号修改捕获消息。 例如,我希望记录消息的行号为 -20。

test.py:40: DeprecationWarning: xxxxxx.

test.py:20: DeprecationWarning: xxxxxx.

这是我到目前为止所拥有的:

class MyHandle(logging.Handler):
    def __init__(self, message_list):
        logging.Handler.__init__(self)
        self.message_list= message_list
    def emit(self, record):        
        self.message_list.append(record.getMessage())

行号是一个日志记录属性,您可以使用自定义日志记录工厂 ( docs ) 修改这些属性中的任何一个或添加新属性。

"""custom_log.py"""
import logging

logging.basicConfig(format="[Line: %(lineno)d] %(message)s")

old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs) # get the unmodified record
    record.lineno += 5 # change the original `lineno` attribute
    return record

logging.setLogRecordFactory(record_factory)

logging.warning("This is line 14")
$ python3 custom_log.py
[Line: 19] This is line 14

暂无
暂无

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

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