python - Pass custom value to the logger instead of to every message -


i want log user session. code follows (setting formatter , handlers omitted):

logger = logging.getlogger("component") logger.info("message", extra={"session": 123}) logger.debug("debug", extra={"session": 123}) 

if there several messages logged, it's annoying send information each time. best/cleanest/most pythonic way achieve that:

logger = logging.getlogger("component") # example: logger.addextra({"session": 123}) logger.info("message") # added automatically logger.debug("debug") # added automatically 

i think of extending logger , overriding logging methods.

create loggeradapter @dhruvpathak specified. according loggeradapters signature:

class logging.loggeradapter(logger, extra) 

you providing logger instance , extra args during initialization:

logger = logging.loggeradapter(logger, extra) 

Comments