Nginx的日志格式可以通过log_format
指令进行自定义配置,以下是全面的配置指南:
在nginx.conf配置文件中(通常在http
块中)配置日志格式:
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 |
本地时间(Common Log Format) |
$request |
完整的原始请求行 |
$status |
响应状态码 |
$body_bytes_sent |
发送给客户端的字节数(不含头) |
$http_referer |
请求来源页 |
$http_user_agent |
客户端浏览器信息 |
$http_x_forwarded_for |
代理服务器IP链 |
$request_time |
请求处理时间(秒) |
$upstream_response_time |
后端服务器响应时间 |
log_format timed_combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
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"}';
log_format ssl_combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$ssl_protocol/$ssl_cipher';
可以为不同server或location配置不同的日志:
server {
access_log /var/log/nginx/example.com.access.log main;
access_log /var/log/nginx/example.com.timing.log timed_combined;
location /api/ {
access_log /var/log/nginx/api.access.log json_combined;
}
}
建议使用logrotate管理日志文件,示例配置:
/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
}
对于高流量站点,可以缓冲日志写入:
access_log /path/to/log.gz combined gzip=1 buffer=32k flush=5m;
可以关闭不需要的日志记录:
access_log off; # 完全关闭访问日志
对于静态文件,可以单独配置不记录:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
access_log off;
}
通过合理配置日志格式,可以更好地监控和分析Nginx服务器的运行状况。