温馨提示×

debian nginx日志太大咋处理

小樊
51
2026-09-01 09:14:21
栏目: 智能运维

在 Debian 上 Nginx 日志太大,常见处理方式有 日志切割、压缩归档、限制大小、关闭不必要日志、集中清理 等。下面按「实用程度」给你一套做法。


一、最推荐:用 logrotate 自动切割(Debian 默认就有)

Debian 一般已安装 logrotate,Nginx 也自带配置。

1. 查看现有配置

cat /etc/logrotate.d/nginx

典型内容类似:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

2. 常用优化建议

  • daily → 每天切(也可 size 100M
  • rotate 7~14 → 保留天数
  • compress → 压缩旧日志
  • size 100M → 超过才切(适合访问量暴增)

示例(按大小切):

/var/log/nginx/*.log {
    size 100M
    rotate 10
    compress
    missingok
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

3. 手动测试

logrotate -d /etc/logrotate.d/nginx   # 模拟
logrotate -f /etc/logrotate.d/nginx   # 强制执行

二、紧急清理(马上见效)

# 只看大小
du -sh /var/log/nginx/*

# 清空(不删文件,Nginx 不中断)
truncate -s 0 /var/log/nginx/access.log
truncate -s 0 /var/log/nginx/error.log

⚠️ 不要直接 rm,否则 Nginx 还占用 inode。


三、减少日志量(治本)

1. 关闭不需要的 access log

server {
    access_log off;
}

或只记录错误:

access_log /var/log/nginx/access.log compression;

2. 忽略静态文件(强烈推荐)

location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
    access_log off;
}

3. 降低 error 日志级别

error_log /var/log/nginx/error.log warn;

四、用系统 journal / 外部方案(进阶)

  • 访问量巨大:接 rsyslog / filebeat → ES
  • 不想存本地:直接 access_log syslog:server=...;
  • 容器环境:日志交给 docker log driver

五、一键排查脚本(给你参考)

du -sh /var/log/nginx/*
ls -lh /var/log/nginx/
logrotate -d /etc/logrotate.d/nginx

如果你愿意,可以告诉我:

  • access.log 还是 error.log 大?
  • 每天大概多大?
  • Nginx 是源装 / apt / docker?

我可以直接帮你写一份 最合适的 logrotate + nginx 配置

0