如何将 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
要更改默认日志,您必须扩展现有的 werkzeug 实现。
相关实现可以参见以下链接:
https://github.com/pallets/werkzeug/blob/main/src/werkzeug/serving.py
此日志记录通过以下方法进行:
要添加用户代理,您必须:
实现它的示例代码:
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)