为啥在 gunicorn 上运行的烧瓶应用程序中使用日志轮换时同时在多个文件上写入日志?

Posted

技术标签:

【中文标题】为啥在 gunicorn 上运行的烧瓶应用程序中使用日志轮换时同时在多个文件上写入日志?【英文标题】:Why writing logs on multiple files at the same time when using log rotation in my flask application running on gunicorn?为什么在 gunicorn 上运行的烧瓶应用程序中使用日志轮换时同时在多个文件上写入日志? 【发布时间】:2021-01-09 14:26:28 【问题描述】:

我在 gunicorn 上运行我的烧瓶 Web 应用程序并使用 RotatingFileHandler 进行日志记录。 我发现我的应用程序正在访问多个日志记录文件,包括要记录的回溯文件,并且我可以观察到日志记录目录中所有文件的大小都在变大。

我不知道为什么会这样。 你有类似的经历或对这个问题有什么想法吗? 当文件大小未达到最大大小时旋转文件。

number of gunicorn workers = 9

logging_config = dict(
    disable_existing_loggers=False,
    formatters=
        'simple_formatter': 'format': '%(message)s'
    ,
    handlers=
        'file_handler': 
            'class': 'logging.handlers.RotatingFileHandler',
            'formatter': 'simple_formatter',
            'filename': 'applog.log',
            'maxBytes': 10 * 1024 * 1024,
            'backupCount': 10
           ,
    ,

    root=
        'handlers': ['file_handler'],
        'level': logging.DEBUG,
    
)


-rw-rw-r-- 1 2.5M Sep 23 11:29 applog.log
-rw-rw-r-- 1 1.9M Sep 23 11:29 applog.log.1
-rw-rw-r-- 1 2.3M Sep 23 11:29 applog.log.2
-rw-rw-r-- 1 5.5M Sep 23 11:29 applog.log.3
-rw-rw-r-- 1 2.0M Sep 23 11:29 applog.log.4
-rw-rw-r-- 1 4.4M Sep 23 11:29 applog.log.5
-rw-rw-r-- 1 2.7M Sep 23 11:29 applog.log.6
-rw-rw-r-- 1 2.6M Sep 23 11:29 applog.log.7
-rw-rw-r-- 1 7.1M Sep 23 11:29 applog.log.8
-rw-rw-r-- 1  10M Sep 23 11:21 applog.log.9

【问题讨论】:

【参考方案1】:

不支持从多个进程写入同一个文件,但乍一看似乎可行。这就是gunicorn 的情况。使用the one described in the logging cookbook 之类的方法来处理这种情况 - 只有一个进程应该写入文件。

【讨论】:

以上是关于为啥在 gunicorn 上运行的烧瓶应用程序中使用日志轮换时同时在多个文件上写入日志?的主要内容,如果未能解决你的问题,请参考以下文章

在烧瓶/gunicorn 中初始化应用程序的位置

使用 nginx 和 gunicorn 运行烧瓶应用程序

如何在 docker 上运行 gunicorn

如何使用 gunicorn 运行模块?

Gunicorn 多个烧瓶工人和绑定任务 celery

gunicorn 访问日志格式