gpt4 book ai didi

python - 如何自定义 Tornado 的访问日志

转载 作者:可可西里 更新时间:2023-11-01 16:09:14 28 4
gpt4 key购买 nike

我有一个通过 Tornado 运行的 Flask 应用程序:

import os
import logging
import sys
from flask import Flask, request, jsonify
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop

app = Flask(__name__)

@app.route("/test", methods=["GET"])
def healthz():
return jsonify(message="OK!"), 200

@app.errorhandler(404)
def not_found(error):

return jsonify(error="Requested page does not exist."), 404

def run_app():

http_server = HTTPServer(WSGIContainer(app))
http_server.listen(port=9000)
IOLoop.instance().start()

if __name__ == '__main__':

logFormat = "timestamp=%(asctime)s pid=%(process)d loglevel=%(levelname)s %(message)s"
logging.basicConfig(
stream=sys.stdout,
level=logging.INFO,
format=logFormat
)

run_app()

我正在使用自定义日志并获得如下输出:

timestamp=2016-11-05 12:26:39,287 pid=23356 loglevel=INFO 200 GET /test (10.0.2.2) 0.63ms
timestamp=2016-11-05 12:26:10,306 pid=23356 loglevel=WARNING 404 GET / (10.0.2.2) 0.67ms

如何修改Tornado的访问日志显示如下:

status_code=200 method=GET URL=/test ip=10.0.2.2 duration=0.63ms

所以我最终在标准输出中得到了这个:

timestamp=2016-11-05 12:26:10,306 pid=23356 loglevel=INFO status_code=200 method=GET URL=/test ip=10.0.2.2 duration=0.63ms

最佳答案

我将覆盖 WSGIContainer 的日志功能:

from tornado.log import access_log
from tornado.wsgi import WSGIContainer

class MyWSGI(WSGIContainer):
def _log(self, status_code, request):
if status_code < 400:
log_method = access_log.info
elif status_code < 500:
log_method = access_log.warning
else:
log_method = access_log.error

request_time = 1000.0 * request.request_time()
log_method(
"status_code=%s method=%s URL=%s ip=%s duration=%.2fms",
status_code, request.method,
request.uri, request.remote_ip, request_time)

然后使用 MyWSGI 代替 WSGIContainer。

关于python - 如何自定义 Tornado 的访问日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40438286/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com