Logging response body in Flask WSGI request/response wrapper

1.6k views Asked by At

I'm working on a Flask application and want to log incomming requests and outgoing responses before Flask kicks in. To do this I am using a wrapper around WSGI. I have it working for the request part, but need some pointers on the response part.

This is the code I have so far.

import logging
import pprint

from cStringIO import StringIO

log = logging.getLogger(__name__)


class WSGIRequestResponseLogging(object):
    """
    This wrapper works independently from Flask and wraps the WSGI application. It shows exactly what
    request is going in and what response is going out.

    http://werkzeug.pocoo.org/docs/0.11/wrappers/
    """

    def __init__(self, app):
        self._app = app

    def __call__(self, environ, start_response):
        log.debug(pprint.pprint(('REQUEST', environ)))

        if environ.get('REQUEST_METHOD') == 'POST':
            length = environ.get('CONTENT_LENGTH', '0')
            length = 0 if length == '' else int(length)

            if length == 0:
                log.debug("REQUEST_BODY: EMPTY")
            else:
                body = environ['wsgi.input'].read(length)
                log.debug("REQUEST_BODY: " + body)
                # After reading the body it is removed, restore it
                environ['wsgi.input'] = StringIO(body)

        def log_response(status, headers, *args):
            log.debug(pprint.pprint(('RESPONSE', pprint.pprint(('RESPONSE', status, headers)))))

            return start_response(status, headers, *args)

        return self._app(environ, log_response)

How can I log the response body in log_response?

Regards, nidkil

1

There are 1 answers

1
Graham Dumpleton On

See the example code on the mod_wsgi site at:

It should work with any WSGI server.

If you were using mod_wsgi-express, this auditing feature is builtin.

mod_wsgi-express start-server --enable-recorder wsgi.py