Reputation: 706
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 -
Upvotes: 37
Views: 38935
Reputation: 1121148
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
.
Upvotes: 76
Reputation: 5655
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)
Upvotes: 0