日志管理
Nginx 日志是排查问题、分析流量的重要工具,下面介绍日志配置与管理方法。
访问日志
启用访问日志
nginx
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 地址 |
$remote_user | 认证用户名 |
$time_local | 请求时间 |
$request | 请求行(方法+URL+协议) |
$status | 响应状态码 |
$body_bytes_sent | 响应体字节数 |
$http_referer | 来源页面 |
$http_user_agent | 客户端浏览器信息 |
$request_time | 请求处理时间(秒) |
按站点分离日志
nginx
server {
listen 80;
server_name www.example.com;
access_log /var/log/nginx/example.com.access.log main;
error_log /var/log/nginx/example.com.error.log;
}
错误日志
配置错误日志
nginx
error_log /var/log/nginx/error.log warn;
日志级别
| 级别 | 说明 |
|---|---|
debug | 调试信息,最详细 |
info | 一般信息 |
notice | 重要提示 |
warn | 警告信息(推荐) |
error | 错误信息(推荐生产) |
crit | 严重错误 |
alert | 需立即处理 |
emerg | 紧急状态 |
注意事项
- 生产环境建议使用
warn或error级别,避免磁盘写满debug级别仅在编译时启用--with-debug时可用- 可在不同层级(main/http/server/location)分别配置日志
条件日志
按条件记录日志,例如只记录特定状态码:
nginx
map $status $loggable {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/important.log combined if=$loggable;
日志缓冲
提高日志写入性能:
nginx
access_log /var/log/nginx/access.log main buffer=32k flush=10s;
buffer=32k:缓冲区大小 32KBflush=10s:最多 10 秒强制刷新
日志轮转
使用 logrotate 管理日志文件,避免单文件过大:
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
}
注意事项
kill -USR1通知 Nginx 重新打开日志文件,无需重启服务- logrotate 配置位于
/etc/logrotate.d/nginx- 建议保留 14 天日志,启用压缩节省空间
关闭日志
特定路径不记录访问日志:
text
location /health {
access_log off;
return 200 "OK";
}
要点总结
- access_log 配置访问日志,error_log 配置错误日志
- log_format 自定义日志格式,使用变量提取关键信息
- 错误日志级别从 debug 到 emerg,生产建议 warn 或 error
- 条件日志可按状态码等条件过滤记录
- 日志轮转使用 logrotate,通过 USR1 信号通知 Nginx 重开日志
- 健康检查等高频接口建议关闭访问日志
📝 发现内容有误?点击此处直接编辑