Nginx 日志主要分为访问日志(access log)和错误日志(error log),可以在 nginx.conf 或 server {} / location {} 中配置。下面给你一个常用且清晰的配置说明。
记录 Nginx 运行时的错误信息(启动失败、404 未捕获原因等)。
error_log /var/log/nginx/error.log warn;
日志级别(越低越详细):
debug < info < notice < warn < error < crit < alert < emerg
✅ 生产环境建议:warn 或 error
记录每一次 HTTP 请求。
access_log /var/log/nginx/access.log;
http {
error_log /var/log/nginx/error.log warn;
access_log /var/log/nginx/access.log;
...
}
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example_access.log;
error_log /var/log/nginx/example_error.log;
}
location /api/ {
access_log /var/log/nginx/api_access.log;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
}
| 变量 | 含义 |
|---|---|
| $remote_addr | 客户端 IP |
| $request | 请求方法和 URL |
| $status | HTTP 状态码 |
| $body_bytes_sent | 返回体大小 |
| $http_user_agent | User-Agent |
| $http_referer | 来源页面 |
| $request_time | 请求耗时 |
access_log off;
error_log off;
⚠️ 不建议完全关闭,至少保留错误日志。
Nginx 不会自动切割日志,一般配合 logrotate。
示例 /etc/logrotate.d/nginx:
/var/log/nginx/*.log {
daily
rotate 7
missingok
notifempty
compress
sharedscripts
postrotate
nginx -s reload
endscript
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
error_log /var/log/nginx/error.log warn;
}
✅ buffer + flush 可以减少磁盘 IO
如果你能告诉我:
我可以帮你给出更贴近你场景的配置模板。