Nginx提供了灵活的日志配置选项,主要包括访问日志(access_log)和错误日志(error_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;
}
error_log /var/log/nginx/error.log warn; # warn级别及以上会记录
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.com.access.log main;
error_log /var/log/nginx/example.com.error.log;
}
# 只记录状态码为4xx和5xx的请求
map $status $loggable {
~^[23] 0;
default 1;
}
server {
access_log /var/log/nginx/error_requests.log main if=$loggable;
}
access_log /var/log/nginx/access.log main buffer=32k gzip flush=5m;
Nginx提供了许多内置变量可用于日志格式:
$remote_addr
- 客户端IP地址$remote_user
- 客户端用户名(基本认证)$time_local
- 本地时间$request
- 完整的请求行$status
- 响应状态码$body_bytes_sent
- 发送给客户端的字节数$http_referer
- 请求来源页$http_user_agent
- 客户端浏览器信息$http_x_forwarded_for
- 代理服务器IP链$request_time
- 请求处理时间(秒)$upstream_response_time
- 后端服务器响应时间建议设置日志轮转以防止日志文件过大:
创建/etc/logrotate.d/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
}
对于高流量网站,考虑:
buffer
参数)生产环境建议将日志级别设置为warn
或error
,避免记录过多调试信息
定期检查日志文件大小并实施轮转策略
现代日志分析工具通常偏好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",'
'"request_time":"$request_time",'
'"http_referrer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
access_log /var/log/nginx/access.json json_combined;
通过以上配置,您可以灵活地控制Nginx的日志记录行为,满足不同场景下的需求。