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>Such <a href="https://docs.python.org/2/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output" rel="nofollow">custom logging</a> is feasible in python logging class, using logging.loggerAdapters which modify the logging behaviour.</p>

<blockquote>
  <p>An easy way in which you can pass contextual information to be output
  along with logging event information is to use the LoggerAdapter
  class. This class is designed to look like a Logger, so that you can
  call debug(), info(), warning(), error(), exception(), critical() and
  log(). These methods have the same signatures as their counterparts in
  Logger, so you can use the two types of instances interchangeably.</p>
</blockquote>

python python-3.x logging