温馨提示×

nginx日志过大如何优化

小樊
58
2026-09-04 11:05:33
栏目: 编程语言

Nginx 日志过大通常可以从日志级别、日志内容、切割归档、异步写入、磁盘与采集方式几个方向来优化。下面按「立竿见影 → 长期方案」给你一套实用做法。


一、先止血:减少日志量(最直接)

1. 降低日志级别

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

常用级别(从少到多):

  • crit < error < warn < notice < info < debug

生产环境一般用 warn 或 error

2. 关闭 access_log(或按需记录)

如果某些接口不需要日志:

location /health {
    access_log off;
}

或完全关闭:

access_log off;

二、精简 access_log 内容

1. 使用更简单的日志格式

默认 combined 日志很大,可自定义:

log_format minimal '$remote_addr - $request_time $status';
access_log /var/log/nginx/access.log minimal;

2. 不记录静态资源

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

三、日志切割(必须做)

1. 使用 logrotate(推荐)

/etc/logrotate.d/nginx 示例:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    sharedscripts
    postrotate
        nginx -s reload
    endscript
}

效果:

  • 每天切
  • 保留 14 天
  • 自动压缩

四、异步 & 高性能写入

1. 使用 buffer(强烈推荐)

access_log /var/log/nginx/access.log main buffer=64k flush=1m;

优点:

  • 减少磁盘 IO
  • 提升性能

2. 开启 gzip 压缩旧日志

logrotate 中已加 compress 即可


五、架构级优化(量大时)

1. 日志集中化(ELK / Loki / SLS)

  • Nginx 只保留短时间
  • 日志发到消息队列或日志系统

2. 使用 syslog 代替文件

access_log syslog:server=127.0.0.1:514 main;

六、检查是否有“异常写日志”

常见问题:

  • 被刷接口(爬虫、攻击)
  • 404 暴增
  • upstream 错误循环

可快速看:

tail -f /var/log/nginx/access.log
awk '{print $9}' access.log | sort | uniq -c | sort -nr

推荐组合(生产最优)

✅ warn 错误日志
✅ buffer + flush
✅ logrotate 每日压缩
✅ 静态资源 access_log off
✅ 非核心接口不记录

如果你愿意,可以贴一段 nginx.conf 或日志样本,我可以直接帮你改成“最小日志方案”。

0 踩