How to enrich logging messages with request information in flask?
<p>I have a small Flask app that's used like a REST API that implements many methods like this:</p>

<pre><code>@route('/do/something', methods=['POST'])
def something():
    app.logger.debug("got request to /do/something")
    result = something_implementation(request.json())
    app.logger.debug("result was %s", str(result))
    return flask.Response(result)
</code></pre>

<p>I would like to enrich these log messages automatically with information from the request object such as header information, parts of the body and whatever else is convenient. </p>

<p>How do I do that in an elegant and pythonic way?</p>

<p>Of course I could just wrap app.logger in my own function and pass the request object and the message along, but there's got to be a nicer and easier way I'm missing.</p>

<p>I usually include something like this in my app.py file to log debug information for each request, along with handling standard errors:</p>

<pre><code># Useful debugging interceptor to log all values posted to the endpoint
@app.before_request
def before():
    values = 'values: '
    if len(request.values) == 0:
        values += '(None)'
    for key in request.values:
        values += key + ': ' + request.values[key] + ', '
    app.logger.debug(values)

# Useful debugging interceptor to log all endpoint responses
@app.after_request
def after(response):
    app.logger.debug('response: ' + response.status + ', ' + response.data.decode('utf-8'))
    return response

# Default handler for uncaught exceptions in the app
@app.errorhandler(500)
def internal_error(exception):
    app.logger.error(exception)
    return flask.make_response('server error', 500)

# Default handler for all bad requests sent to the app
@app.errorhandler(400)
def handle_bad_request(e):
    app.logger.info('Bad request', e)
    return flask.make_response('bad request', 400)v
</code></pre>

python logging flask