簡體   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