Pass custom value to the logger instead of to every message
<p>I want to log the user session. Currently the code is as follows (setting formatter and handlers is omitted):</p>

<pre><code>logger = logging.getLogger("component")
logger.info("message", extra={"session": 123})
logger.debug("debug", extra={"session": 123})
</code></pre>

<p>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:</p>

<pre><code>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
</code></pre>

<p>I could think of extending the logger and overriding logging methods.</p>

<p>Use function factories for instance like that</p>

<pre><code>def get_logger_with_context(name, context=None):
    extra = context or {}
    logger = logging.getLogger(name)

    def log(level, message, **kwargs):
        getattr(logger, level)(message, extra=context)

    return log
</code></pre>

python python-3.x logging