Nginx提供了灵活的日志记录功能,可以帮助管理员监控访问情况、排查问题以及分析流量。以下是Nginx日志配置的详细说明:
Nginx主要有两种日志: - 访问日志(access log):记录所有客户端请求 - 错误日志(error log):记录服务器错误和警告
在nginx.conf
或虚拟主机配置文件中:
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;
}
error_log /var/log/nginx/error.log warn;
# 日志级别:debug, info, notice, warn, error, crit, alert, emerg
# 只记录特定状态码的请求
map $status $loggable {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/access.log main if=$loggable;
# 排除特定请求(如静态文件)
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
access_log off;
}
# 在server块中使用变量实现按天分割
if ($time_iso8601 ~ "^(\d{4}-\d{2}-\d{2})") {
set $day $1;
}
access_log /var/log/nginx/access-$day.log main;
常用日志变量:
变量 | 说明 |
---|---|
$remote_addr |
客户端IP地址 |
$remote_user |
认证用户名 |
$time_local |
本地时间 |
$request |
请求行(GET/POST等) |
$status |
响应状态码 |
$body_bytes_sent |
发送给客户端的字节数 |
$http_referer |
来源页面 |
$http_user_agent |
客户端浏览器信息 |
$http_x_forwarded_for |
代理服务器IP链 |
使用logrotate
管理日志文件:
/etc/logrotate.d/nginx
:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
/usr/bin/systemctl reload nginx > /dev/null 2>&1 || true
endscript
}
对于日志分析工具,JSON格式更方便:
log_format json_combined escape=json
'{"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"remote_user":"$remote_user",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent",'
'"http_x_forwarded_for":"$http_x_forwarded_for",'
'"request_time":$request_time,'
'"upstream_response_time":"$upstream_response_time"}';
access_log /var/log/nginx/access.json json_combined;
临时增加调试日志:
error_log /var/log/nginx/debug.log debug;
调试完成后记得恢复为正常级别。
通过合理配置Nginx日志,您可以更好地监控服务器运行状况、分析访问模式和快速定位问题。