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>Create a <code>LoggerAdapter</code> as @DhruvPathak specified. According to <a href="https://docs.python.org/3/library/logging.html#logging.LoggerAdapter" rel="nofollow"><code>LoggerAdapter</code>s signature</a>:</p>

<pre><code>class logging.LoggerAdapter(logger, extra)
</code></pre>

<p>you do that by providing your logger instance and the <code>extra</code> args during initialization:</p>

<pre><code>logger = logging.LoggerAdapter(logger, extra)
</code></pre>

python python-3.x logging