Dumping HTTP requests with Flask

flask, python

Solution

Flask makes a standard logger available at at `current_app.logger`, there's an example configuration in this gist, though you can centralise the logging calls in a before_request handler if you want to log every request:

from flask import request, current_app

@app.before_request
def log_request():
    if current_app.config.get('LOG_REQUESTS'):
        current_app.logger.debug('whatever')
        # Or if you dont want to use a logger, implement
        # whatever system you prefer here
        # print request.headers
        # open(current_app.config['REQUEST_LOG_FILE'], 'w').write('...')

Problem

I am developing a Flask application based web application ( https://github.com/opensourcehacker/sevabot ) which has HTTP based API services. Many developers are using and extending the API and I'd like to add a feature which prints Flask's HTTP request to Python logging output, so you can see raw HTTP payloads, source IP and headers you get. What hooks Flask offers where this kind of HTTP request dumping would be the easiest to implement Are there any existing solutions and best practices to learn from?

Original source