【问题标题】:Connexion Flask logging formattingConnexion Flask 日志记录格式
【发布时间】:2021-03-15 17:13:20
【问题描述】:

我正在努力使用 gevent 服务器设置连接烧瓶休息 api 的日志记录。我只想在每个请求之后记录消息,例如GET /health HTTP/1.1,或者更好的是只记录 http 状态代码,例如200。在创建应用程序之前,我遵循烧瓶文档并设置dictConfig。像这样:

import connexion
from logging.config import dictConfig


def main():
    app = connexion.App(__name__)
    app.app.logger.info('This is a check!')
    app.add_api('swagger.yaml')
    app.run(server='gevent')

if __name__ == '__main__':

    dictConfig({
        'version': 1,
        'formatters': {'default': {
            'format': 'Custom message: %(message)s',
        }},
        'handlers': {'wsgi': {
            'class': 'logging.StreamHandler',
            'stream': 'ext://flask.logging.wsgi_errors_stream',
            'formatter': 'default'
        }},
        'root': {
            'level': 'INFO',
            'handlers': ['wsgi']
        }
    })

    main()

启动应用并在发送两个请求(一个 200 和一个 405)后:

Custom message: This is a check!
127.0.0.1 - - [2021-03-15 12:42:35] "GET /health HTTP/1.1" 200 126 0.001714
127.0.0.1 - - [2021-03-15 12:42:35] "PUT /health HTTP/1.1" 405 275 0.000711

所以,在app.run() 之前,app.app.logging() 看起来不错,只发送消息Custom message: This is a check!,但之后日志不再遵循字典。 知道我做错了什么吗?

【问题讨论】:

    标签: python flask python-logging connexion


    【解决方案1】:

    据我所知,dictConfig 没有被使用,因为你没有将它分配给任何东西。

    你需要类似的东西

    logging.config.dictConfig(yourconfig)
    

    yourconfig 是你的 dictConfig。将您的 dictConfig 移动到 main() 以使其在同一范围内,或者如果您选择将其分开,则从文件中导入它。

    见:Logging Cookbook

    【讨论】:

    • 谢谢,如果server 不是gevent,这将按预期工作,因此只需使用app.run()。不幸的是,如果使用gevent,则不会。
    • 知道如何只记录 200 状态码吗?我没想到使用%(message) 我得到127.0.0.1 - - [2021-03-15 12:42:35] "GET /health HTTP/1.1" 200 126 0.001714。这是我认为标准的werkzeug 日志,我不知道如何更改它
    猜你喜欢
    • 2019-01-14
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 2018-01-22
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多