gunicorn 自定义日志

gunicorn 自定义日志

默认情况下,如果只通过errorlogaccesslog参数指定 gunicorn 的日志文件,日志文件会一直增长,最后导致硬盘占用过大和检查日志不方便。因此需要自定义配置滚动日志保存。

配置文件

直接在 gunicorn 的配置文件 gunicorn_conf.py 中添加logconfig_dict配置项

import multiprocessing

bind = '0.0.0.0:8000'
workers = multiprocessing.cpu_count() * 2 + 1
backlog = 2048
debug = False
timeout = 500
daemon = True
pidfile = './logs/gunicorn.pid'
logconfig_dict = {
    'version': 1,
    'disable_existing_loggers': False,
    'root': {'level': 'INFO', 'handlers': ['console']},
    'loggers': {
        'gunicorn.error': {
            'level': 'INFO',
            'handlers': ['error_file'],
            'propagate': False,
            'qualname': 'gunicorn.error'
        },
        'gunicorn.access': {
            'level': 'INFO',
            'handlers': ['access_file'],
            'propagate': False,
            'qualname': 'gunicorn.access'
        }
    },
    'handlers': {
        # 必须配置 console handler,root logger 默认使用 console handler
        # 或者在 root 中指定自定义的 handler
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'generic',
            'stream': 'ext://sys.stdout'
        },
        'error_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': './logs/gunicorn.error.log',
            'maxBytes': 5 * 1024 * 1024,
            'backupCount': 5,
            'formatter': 'generic'
        },
        'access_file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': './logs/gunicorn.access.log',
            'maxBytes': 5 * 1024 * 1024,
            'backupCount': 5,
            'formatter': 'generic'
        },
    },
    'formatters': {
        'generic': {
            'format': '%(asctime)s [%(process)d] [%(levelname)s] %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S %z',
            'class': 'logging.Formatter'
        }
    }
}

问题

将 19 版本的配置直接复制到 22 版的 gunicorn 中使用时,出现Error: Unable to configure root logger报错。
通过对比 gunicorn 的CONFIG_DEFAULTS配置,发现在老版本中不需要考虑 root logger 的问题,在新版本中,gunicorn 会有一个默认的 root logger,并且使用的 handler 是 console,如果在 handlers 中没有配置就会导致报错。
解决方法:

  1. 在 handler 中配置 console handler
  2. 增加配置 root logger 配置项,并指定已有的 handler
posted @ 2024-07-06 11:02  守望人间  阅读(815)  评论(0)    收藏  举报