Nginx提供了灵活的日志记录功能,可以通过配置记录详细的访问信息。以下是配置详细日志记录的方法:
在nginx.conf或站点配置文件中,可以自定义访问日志格式:
http {
log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$upstream_addr $upstream_status '
'$ssl_protocol $ssl_cipher '
'"$http_x_forwarded_for"';
access_log /var/log/nginx/access.log detailed;
}
error_log /var/log/nginx/error.log warn;
日志级别可选:
- debug
(最详细)
- info
- notice
- warn
- error
- crit
- alert
- emerg
(最少信息)
变量 | 描述 |
---|---|
$remote_addr |
客户端IP地址 |
$remote_user |
认证用户名 |
$time_local |
本地时间 |
$request |
完整的请求行(GET / HTTP/1.1) |
$status |
响应状态码 |
$body_bytes_sent |
发送给客户端的字节数 |
$http_referer |
请求来源页面 |
$http_user_agent |
客户端浏览器信息 |
$http_x_forwarded_for |
代理服务器IP链 |
$request_time |
请求处理时间(秒) |
$upstream_response_time |
后端服务器响应时间 |
$upstream_addr |
后端服务器地址 |
$upstream_status |
后端服务器响应状态码 |
$ssl_protocol |
SSL协议版本 |
$ssl_cipher |
使用的加密套件 |
map $status $loggable {
~^[23] 0; # 不记录2xx和3xx响应
default 1; # 记录其他响应
}
access_log /var/log/nginx/error_requests.log combined if=$loggable;
默认情况下Nginx不记录POST请求体,如需记录需要额外配置:
log_format postdata '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$request_body"';
server {
location / {
access_log /var/log/nginx/postdata.log postdata;
# 其他配置...
}
}
建议设置日志轮转以防止日志文件过大:
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
/etc/init.d/nginx reload > /dev/null
endscript
}
debug
级别,会产生大量日志配置完成后,记得测试并重新加载Nginx配置:
nginx -t && nginx -s reload