I'm using gunicorn to run my Flask app.
I have an user_id
on Flask's global g
object that I want to log on each authenticated request.
Does anyone know a good way to do that? I tried adding a custom filter like this, but the request doesn't seem to be in scope at the time the logger is executed:
class MyFilter(logging.Filter):
def filter(self, record):
if hasattr(g, 'user_id'):
record.msg = "User ID: {0} ".format(g.user_id) + record.msg
return 1
I'm expecting something like this:
2014-11-08 21:52:15 [INFO] REQUESTLOG 127.0.0.1 User ID: 12345 "GET /v1.0/healthcheck HTTP/1.1" 200 51 "-" "curl/7.35.0"
Thanks!
You can subclass the Werkzeug request handler and provide your own version of the log_request()
method. Here is an example:
from werkzeug.serving import BaseRequestHandler
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "hi"
class MyRequestHandler(BaseRequestHandler):
def log_request(self, code='-', size='-'):
self.log('info', 'custom log! "%s" %s %s', self.requestline, code, size)
if __name__ == '__main__':
app.run(debug=True, request_handler=MyRequestHandler)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.