0 votes
ago in Education by (1.7m points)
I want to log the user session. Currently the code is as follows (setting formatter and handlers is omitted):

logger = logging.getLogger("component")

logger.info("message", extra={"session": 123})

logger.debug("debug", extra={"session": 123})

If there are several messages to be logged, it's annoying to send this extra information each time. What would be the best/cleanest/most pythonic way to achieve something like that:

logger = logging.getLogger("component")

# for example:

logger.addExtra({"session": 123})

logger.info("message") # extra would be added automatically

logger.debug("debug") # extra would be added automatically

I could think of extending the logger and overriding logging methods.

JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
ago by (1.7m points)
Create a LoggerAdapter as @DhruvPathak specified. According to LoggerAdapters signature:

class logging.LoggerAdapter(logger, extra)

you do that by providing your logger instance and the extra args during initialization:

logger = logging.LoggerAdapter(logger, extra)