将 UserAgent 信息添加到 Flask 日志中

问题描述 投票:0回答:1

如何将 UserAgent 添加到控制台显示的 Flask 请求日志中?

backend-flask |  * Serving Flask app 'generate-ics'
backend-flask |  * Debug mode: off
backend-flask | WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
backend-flask |  * Running on all addresses (0.0.0.0)
backend-flask |  * Running on http://127.0.0.1:8081
backend-flask |  * Running on http://172.28.0.2:8081
backend-flask | Press CTRL+C to quit
backend-flask | 64.227.xx.xx - - [08/Nov/2024 18:55:44] "GET /rentaldb.ics HTTP/1.1" 200 -
backend-flask | 62.113.xx.xx - - [08/Nov/2024 18:55:46] "GET /rentaldb.ics HTTP/1.1" 200 -
backend-flask | 64.227.xx.xx - - [08/Nov/2024 18:55:49] "GET /rentaldb.ics HTTP/1.1" 200 -
                               ^
                  Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0
python flask logging user-agent
1个回答
0
投票

要更改默认日志,您必须扩展现有的 werkzeug 实现。
相关实现可以参见以下链接:
https://github.com/pallets/werkzeug/blob/main/src/werkzeug/serving.py

此日志记录通过以下方法进行:

  • send_response 调用 log_request
  • log_request调用日志
  • log 写入 Werkzeug 记录器

要添加用户代理,您必须:

  • 创建一个扩展 WSGIRequestHandler 的 CustomRequestHandler 类。
  • 覆盖 log_request 以将 User-Agent 添加到日志消息中
  • 覆盖日志以正确处理消息格式
  • 配置 Flask 以使用我们的自定义处理程序

实现它的示例代码:

import logging
from flask import Flask
from werkzeug.serving import WSGIRequestHandler

class CustomRequestHandler(WSGIRequestHandler):
    def log(self, type, message, *args):
        logger = logging.getLogger('werkzeug')
        getattr(logger, type)(message)

    def log_request(self, code='-', size='-'):
        user_agent = self.headers.get('User-Agent', 'Unknown')
        log_message = f'{self.address_string()} - {user_agent} - [{self.log_date_time_string()}] "{self.requestline}" {code} {size}'
        self.log('info', log_message)

app = Flask(__name__)

@app.route('/')
def home():
    return 'test'

if __name__ == '__main__':
    app.run(debug=True, request_handler=CustomRequestHandler)

© www.soinside.com 2019 - 2024. All rights reserved.