简体   繁体   中英

Python modifying logging message info?

I have a logging handler that logs warning messages to a list. But the way my scripts are constructed, the logged line number of the messages will be offseted. So I wanted to modify the capture messages with my own line number. For example, I want -20 on the line number for my logged messages.

test.py:40: DeprecationWarning: xxxxxx.

test.py:20: DeprecationWarning: xxxxxx.

This is what I have so far:

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())

The line number is a Log Record attribute, you can modify any of these attributes or add new ones by using a custom log record factory ( 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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