如何在gunicorn应用代码中记录自定义日志消息
将应用日志写入Gunicorn日志文件的解决方案
直接用下面两种方法就能让你的代码日志和Gunicorn请求日志写到同一个log.txt里:
方法1:直接使用Gunicorn的Logger实例
在WSGI应用里获取Gunicorn已经配置好的Logger,直接用它打日志:
import logging def app(environ, start_response): # 获取Gunicorn初始化完成的logger logger = logging.getLogger('gunicorn.error') path = environ.get("PATH_INFO") if path == "/abc": logger.info(f'user requested {path}') # 必须返回响应,示例返回简单文本 status = '200 OK' headers = [('Content-Type', 'text/plain')] start_response(status, headers) return [b'Hello World']
方法2:让标准logging复用Gunicorn的配置
如果习惯用logging.info()这种直接调用的方式,只需要在应用第一次运行时把Gunicorn的日志handler加到标准logging里:
import logging def app(environ, start_response): # 仅第一次请求时配置,避免重复添加handler if not logging.getLogger().handlers: gunicorn_logger = logging.getLogger('gunicorn.error') # 把Gunicorn的handler和级别同步给标准logging logging.getLogger().addHandler(gunicorn_logger.handlers[0]) logging.getLogger().setLevel(gunicorn_logger.level) path = environ.get("PATH_INFO") if path == "/abc": logging.info(f'user requested {path}') status = '200 OK' headers = [('Content-Type', 'text/plain')] start_response(status, headers) return [b'Hello World']
注意事项
- 不要在代码里调用
logging.basicConfig(),这会覆盖Gunicorn的日志配置,导致日志写不到指定的log.txt。 - Gunicorn启动时设置的
--log-level 'debug'会自动生效,info级别的日志会被正常写入。
内容的提问来源于stack exchange,提问作者jaycer
相关产品推荐
相关产品推荐

