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>In Java we have Mapped Diagnostic Context (<code>MDC</code>) in <code>Log4j</code> framework.</p>

<p>Basically it is a map. You can put values there which can be used in logger output pattern.</p>

<p>Please take a look at: <a href="https://gist.github.com/mdaniel/8347533" rel="nofollow">https://gist.github.com/mdaniel/8347533</a></p>

<p>I don't know is it working, but maybe <code>MDC</code> will be a key for Your further research.</p>

python python-3.x logging