日志配置与轮转
约 615 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Nginx › 运维与安全(在新窗口打开) › 日志配置与轮转
访问日志(access_log)
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;
server {
# 可以为特定站点覆盖日志路径
access_log /var/log/nginx/example.com.log main;
location /api/ {
# 关闭特定 location 的日志(如健康检查接口)
access_log off;
}
}
}错误日志(error_log)
# 全局错误日志
error_log /var/log/nginx/error.log warn;
# 调试时调低级别
error_log /var/log/nginx/error.log debug;
# 为特定 server 设置
server {
error_log /var/log/nginx/example.com.error.log error;
}| 级别 | 说明 |
|---|---|
emerg | 紧急,系统不可用 |
alert | 必须立即处理 |
crit | 严重错误 |
error | 错误 |
warn | 警告(默认) |
notice | 重要通知 |
info | 信息 |
debug | 调试信息(最详细,影响性能) |
自定义日志格式
# JSON 格式日志(方便日志分析系统解析)
log_format json escape=json '{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"remote_user":"$remote_user",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent",'
'"http_x_forwarded_for":"$http_x_forwarded_for",'
'"upstream_addr":"$upstream_addr",'
'"upstream_status":"$upstream_status",'
'"upstream_response_time":"$upstream_response_time"'
'}';
access_log /var/log/nginx/json.log json;logrotate 日志轮转
通常系统安装 Nginx 时已自动配置 logrotate:
# Ubuntu 默认位置
cat /etc/logrotate.d/nginx# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily # 每天轮转
missingok # 日志文件不存在不报错
rotate 14 # 保留 14 份历史
compress # 压缩历史日志
delaycompress # 延迟一天压缩
notifempty # 日志为空不轮转
create 640 nginx adm # 创建新日志的权限和所有者
sharedscripts # 所有日志轮转后只执行一次 postrotate
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 $(cat /var/run/nginx.pid) # 通知 Nginx 重新打开日志
fi
endscript
}手动轮转测试:
sudo logrotate -vf /etc/logrotate.d/nginx条件日志
# map 条件控制是否记录日志
map $uri $loggable {
/health 0; # 健康检查不记录
/status 0;
default 1;
}
server {
access_log /var/log/nginx/access.log main if=$loggable;
}日志字段说明
| 变量 | 示例 | 说明 |
|---|---|---|
$remote_addr | 203.0.113.5 | 客户端 IP |
$time_local | 15/May/2026:10:30:00 +0800 | 请求时间 |
$request | GET /api/users HTTP/1.1 | 请求行 |
$status | 200 | 状态码 |
$body_bytes_sent | 1234 | 响应体字节数 |
$request_time | 0.123 | 请求处理时间(秒) |
$upstream_addr | 10.0.0.1:3000 | 上游服务器地址 |
$upstream_response_time | 0.100 | 上游响应时间 |
小结
access_log记录所有请求,error_log记录错误和调试信息。log_format自定义日志格式,escape=json适合 JSON 日志输出。access_log off关闭特定 location 的日志,if=$variable条件记录。- logrotate 自动轮转日志,通过
kill -USR1(nginx -s reopen)通知 Nginx 重开日志。 $request_time和$upstream_response_time是排查慢请求的关键字段。
上一节:TCP/UDP 负载均衡 下一节:监控与状态页
