My current format string is:
formatter = logging.Formatter('%(asctime)s : %(message)s')
and I want to add a new field called app_name and which will have a different value in each script that contains this formatter.
import logging
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.addHandler(syslog)
But I'm not sure how to pass that app_name
value to the logger to interpolate into the format string. I can obviously get it to appear in the log message but passing it each time but this is messy.
I've tried:
logging.info('Log message', app_name='myapp')
logging.info('Log message', {'app_name', 'myapp'})
logging.info('Log message', 'myapp')
but none work.
You need to pass the dict as a parameter to extra to do it that way.
Proof:
Also, as a note, if you try to log a message without passing the dict, then it will fail.
Another way is to create a custom LoggerAdapter. This is particularly useful when you can't change the format OR if your format is shared with code that does not send the unique key (in your case app_name):
And in your code, you would create and initialize your logger as usual:
Finally, you would create the wrapper adapter to add a prefix as needed:
The output will look something like this:
You could use a LoggerAdapter so you don't have to pass the extra info with every logging call:
logs (something like)
Filters can also be used to add contextual information.
produces a similar log record.