Reputation: 1821
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())
Upvotes: 0
Views: 1709
Reputation: 797
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
Upvotes: 1