I am trying to add a custom format field in my library. I know this is either done with a Filter or a LoggerAdapter object. However, in the examples I have seen (like this one: How do I add custom field to Python log format string?) the custom field they want to generate is static and known when the logger is created.
I need to be able to send a variable to my log record that I really don't know until just before I write the log record. I guess I am just not seeing the solution but how best to accomplish this?
Currently I set up my logger this way:
import logging
class MyClass:
filehandler = logging.handlers.RotatingRileHandler(r'C:\Users\Me\Desktop\Logs',
maxBytes=1000000, backupCount=4, encoding='ASCII')
formatter = logging.Formatter('[%(asctime)s] : %(levelname)-8s: Para: %(parameter)-15s'
' - %(message)s')
# parameter is my custom name I want to inject
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
self.logger.addHandler(file_handler)
d = {'parameter': ''}
self.logger = logging.LoggerAdapter(self.logger, extra=d)
And in my test I write:
my_obj = MyClass()
my_obj.logger.error('This is my error.', extra={'parameter': 'True'}
but this makes the parameter field '' (blank string) always. Is there a way to set up the d dictionary for each time I make the log call (error(), debug(), etc.)?