如何使用gunicorn从代码中记录自定义消息



我有一个gunicorn应用程序在本地运行,它会将请求记录到文本文件中。我不明白的是如何从我的gunicorn应用程序将消息记录到gunicorn日志文件中。要启动我的应用程序,我使用类似% gunicorn --workers=2 test:app --reload --log-file log.txt --log-level 'debug'的命令

我想要这样的代码:

def app(environ, start_response):
path = environ.get("PATH_INFO")
if path == "/abc":
logging.info(f'user requested {path}')

如果这个级别合适的话,让gunicorn写一个信息日志条目。

我查看了文档,发现gunicorn使用类gunicorn.glogging.Logger进行日志记录,但我没有看到任何关于如何实例化该类或使用它记录我自己的消息的文档。

要登录到gunicorn日志文件,必须导入日志并使用字符串"gunicorn.error";

import logging
gunicorn_logger = logging.getLogger('gunicorn.error')

然后你可以做

gunicorn_logger.warning(f'returned 404 for: {path}')

来源如何在带有gunicorn 的Python中使用日志记录模块

最新更新