How can I log request POST body in Flask?

25,540

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())
Share:
25,540

Related videos on Youtube

eplaut
Author by

eplaut

php-python-perl-bash

Updated on November 11, 2020

Comments

  • eplaut
    eplaut over 3 years

    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 -
    
    • Martijn Pieters
      Martijn Pieters almost 9 years
      Flask includes logging setup; app.logger gives you a pre-configured logging logger.
  • Pedro Caseiro
    Pedro Caseiro almost 5 years
    When implementing this solution, please be aware that this logs every request, including login and registration endpoints. You'll log user's passwords in plain text if frontend sends it in plaintext.