Nginx 提供了灵活的日志记录功能,允许管理员自定义日志格式以满足不同的监控、分析和安全需求。以下是关于 Nginx 日志格式实现的详细说明。
Nginx 使用 log_format
指令定义日志格式,然后在 access_log
或 error_log
指令中应用这些格式。
log_format format_name 'string with variables';
access_log /path/to/logfile.log format_name;
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
- 上游服务器响应时间log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
log_format extended '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"';
log_format json_log 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"'
'}';
可以基于条件记录日志:
map $status $loggable {
~^[23] 0; # 不记录2xx和3xx状态
default 1; # 记录其他状态
}
access_log /var/log/nginx/access.log combined if=$loggable;
为提高性能,可以启用日志缓冲和即时压缩:
access_log /var/log/nginx/access.log combined buffer=32k gzip flush=5m;
可以为不同虚拟主机或位置设置不同的日志文件:
server {
server_name example.com;
access_log /var/log/nginx/example.com.access.log combined;
error_log /var/log/nginx/example.com.error.log;
location /api {
access_log /var/log/nginx/api.access.log json_log;
}
}
建议使用 logrotate
管理日志轮转,创建 /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
}
通过灵活配置Nginx日志格式,您可以获得关于服务器性能和用户行为的宝贵见解,同时满足安全和合规要求。