You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Gunicorn重启时清空指定日志文件的问题

解决Gunicorn重启清空日志的问题

方案1:启用内置的日志追加配置

Gunicorn内置了日志追加的配置项,你可以直接在配置文件中添加:

append_log = True

或者启动时通过命令行参数指定:

gunicorn -c your_config.py --append-log

开启后,Gunicorn会以追加模式打开日志文件,重启进程时就不会清空原有日志内容。

方案2:通过Shell重定向接管日志输出

如果内置配置不适用(比如使用较旧版本的Gunicorn),可以放弃Gunicorn自带的日志文件配置,改为将日志输出到标准输出/错误,再通过Shell重定向以追加模式写入文件。

修改配置文件:

accesslog = "-"  # 输出到stdout
errorlog = "-"    # 输出到stderr

启动时执行:

gunicorn -c your_config.py >> /path/to/access.log 2>> /path/to/error.log &

这种方式利用Shell的追加重定向特性,确保每次启动都不会覆盖原有日志。

方案3:用logrotate管理日志(长期运维推荐)

即使暂无法手动备份,logrotate可以自动完成日志轮转并保留历史记录,同时避免日志文件过大。创建logrotate配置文件(例如/etc/logrotate.d/gunicorn):

/path/to/access.log /path/to/error.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 0644 www-data www-data
    sharedscripts
    postrotate
        pkill -F /path/to/pidfile
        gunicorn -c your_config.py &
    endscript
}

该配置会每天轮转日志,保留最近7天的历史日志,轮转完成后自动重启Gunicorn,从根源解决日志清空问题。

内容的提问来源于stack exchange,提问作者Zoltán

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:50:21