How can I log request POST body in Flask?

Question:

I’m using flask server, and I want to log each request data and header (so I can use it afterwards to test my server).
I took the werkzeug logger with

    self._app.log = logging.getLogger('werkzeug')
    self._app.log.addHandler(RotatingFileHandler('log.txt', mode='w'))
    self._app.log.setLevel(logging.DEBUG)

But I don’t understand how to change the log format to include request.data and request.headers, all I have is the default log

    127.0.0.1 - - [17/Feb/2015 17:09:43] "POST /helloworld HTTP/1.1" 200 -
Asked By: eplaut

||

Answers:

How about you create a small helper method, which you call in each and every controller of your flask application.

The helper method will be something like this:

def log_my_request_data(request_data):
   #this method will log this data

and then in all controllers, get the request.data like this

from flask import request

request_data = request.data

and call log_my_request_data(request_data)

Answered By: NIlesh Sharma

You can log additional info for each request with a Flask.before_request hook:

@app.before_request
def log_request_info():
    app.logger.debug('Headers: %s', request.headers)
    app.logger.debug('Body: %s', request.get_data())

This uses the preconfigured logger that comes with Flask, app.logger.

Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.