[英]How can I add an id from flask's global 'g' object in the access log?
I'm using gunicorn to run my Flask app. 我正在使用gunicorn来运行我的Flask应用。
I have an user_id
on Flask's global g
object that I want to log on each authenticated request. 我在Flask的全局g
对象上有一个user_id
,我想登录每个经过身份验证的请求。
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. 您可以将Werkzeug请求处理程序子类化,并提供您自己的log_request()
方法版本。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.