title: Python Logging : how to add a custom field to LogRecord, and register a global callback to sets it's value
body: <p>In a Flask application, I want to add a <code>user_id</code> field added to every error log record that gets produced, whenever a <code>user_id</code> exists in the <code>flask.session</code>.</p>
  
  <p>I came up with the solution below but it's hackish, since it doesn't allow for the format string to drive the formatting of the <code>user_id</code>, and since the logging API seems to provides ways to customize logging (<code>LoggerAdapter</code>, <code>logging.makeRecord</code>, etc...) I figure there has to be a cleaner way. </p>
  
  <p>What would be the "python way" to do it ?  </p>
  
  <pre><code>class CustomFormatter(Formatter):
      def format(self, record):
          from myapp.core import authenticationManager
          user_id = authenticationManager.current_user_id_if_authenticated()
          user_id = "unknown" if user_id is None else str(user_id)
          return super(F,self).format(record) + ", user_id" + user_id
  </code></pre>