0

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

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, this did modified the line number, but when I try to format it like format="[line: %(lineno)d] %(message)s", the message attribute still contains the original line number.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.