gpt4 book ai didi

python-3.x - flask 记录重复输出

转载 作者:行者123 更新时间:2023-12-03 20:16:55 36 4
gpt4 key购买 nike

我想将 flask 日志格式更改为控制台,我试过了,

Provide extra information to Flask's app.logger

但它对我不起作用;它已经超过 3 年了,也许已经过时了?

我可以添加一个额外的控制台处理程序,它可以工作,但是我得到了重复的输出,一次来自 flask 默认控制台处理程序,一次来自我添加的处理程序。

来源,

import sys
import logging
from flask import Flask


def setup_logging(level=logging.INFO):

# FIXME: logs are coming out "twice", once with the format from flask, and again from
# the format from consoleHandler. app.logger level and the console handler
# level seem to be linked
app.logger.setLevel(level)

# Here we define our formatter
FORMAT = "%(relativeCreated)6d %(threadName)15s %(filename)25s:%(lineno)4s - %(name)30s:%(funcName)20s() %(levelname)-5.5s : %(message)s"
formatter = logging.Formatter(FORMAT)

consoleHandler = logging.StreamHandler(stream=sys.stdout)
consoleHandler.setFormatter(formatter)
consoleHandler.setLevel(level)

app.logger.addHandler(consoleHandler)

# this did not work :(
# https://stackoverflow.com/questions/27775026/provide-extra-information-to-flasks-app-logger


app = Flask(__name__)

@app.route('/')
def hello_world():
app.logger.info("Foo Bar")
return 'Hello, World!'


setup_logging()

app.run(host="0.0.0.0", port=6800, debug=False)

输出,
 * Serving Flask app "SO_log_01" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:6800/ (Press CTRL+C to quit)
[2018-07-02 17:35:52,906] INFO in SO_log_01: Foo Bar
127.0.0.1 - - [02/Jul/2018 17:35:52] "GET / HTTP/1.1" 200 -
5083 Thread-1 SO_log_01.py: 39 - flask.app: hello_world() INFO : Foo Bar
127.0.0.1 - - [02/Jul/2018 17:35:55] "GET /favicon.ico HTTP/1.1" 404 -

最佳答案

如果要替换记录器格式,则需要删除以前的记录器处理程序。

app.logger.handlers.clear()
app.logger.addHandler(consoleHandler)

https://code.luasoftware.com/tutorials/flask/change-flask-logging-output-format/

关于python-3.x - flask 记录重复输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51144114/

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