I'm using connexion and Swagger to create an API in Python. I'd like to log all of the incoming calls to a file so I can see what's being requested. I've been able to log the path of the calls I've received but I can't figure out how to log the body.
Here's where I've configured my logging:
if __name__ == '__main__':
import logging
logging.basicConfig(format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s', filename='golden_record.log',level=logging.DEBUG)
When I look into the log, I see the path, as in the following for a POST call...
2019-03-23 12:47:16,182 - werkzeug - INFO - 127.0.0.1 - - [23/Mar/2019 12:47:16] "POST /golden_record/account HTTP/1.1" 400 -
but I don't see the body of the call (i.e. the data I've sent). Is there a way to automatically record this for every call that comes in? Doing so would help debug calls that aren't functioning as desired. Thanks!
Just add a Flask before_request.
Connexion instance stores the Flask instance as the app
attribute, so you can access using app.app
.
Add the code and you will log the body:
@app.app.before_request
def log_request_info():
print('Body: %s', request.get_data())
Change the print
method to your logger:
@app.app.before_request
def log_request_info():
logger.info('Body: %s', request.get_data())
The request
import is :
from flask import request
And the app
is your Connexion instance:
app = connexion.App(__name__, specification_dir="./swagger/")
I created a Gist with the code. https://gist.github.com/kevinmmartins/f832c21215bb51cea73b8fdd28f6d88d