Debian Nginx日志格式选择建议
combinedNginx默认提供combined格式(类似Apache的通用日志格式),适用于大多数基础场景,包含客户端IP、请求时间、方法、URL、状态码、响应大小、引用页、用户代理等关键信息,能满足常规访问统计与问题排查需求。
配置示例:
http {
log_format combined '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
access_log /var/log/nginx/access.log combined;
}
适用场景:小型网站、测试环境或不需要复杂日志分析的场景。
若需更详细的请求信息(如请求处理时间、上游服务器响应时间、SSL协议等),可通过log_format自定义格式。常见扩展字段包括:
$request_time:请求处理时间(毫秒),用于分析性能瓶颈;$upstream_response_time:上游服务器(如PHP-FPM、API)响应时间,定位后端延迟;$ssl_protocol/$ssl_cipher:SSL/TLS协议及加密套件,用于安全审计;$http_x_forwarded_for:客户端真实IP(代理环境下)。推荐配置示例:
http {
log_format detailed '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$request_time $upstream_response_time '
'$ssl_protocol/$ssl_cipher';
access_log /var/log/nginx/access.log detailed;
}
适用场景:生产环境、需要性能分析或安全审计的场景。
若使用ELK(Elasticsearch+Logstash+Kibana)、Loki、Splunk等日志分析工具,可将日志格式设为JSON,方便工具解析字段并实现可视化。需使用escape=json确保字段中的特殊字符(如引号)被正确转义。
配置示例:
http {
log_format json_combined escape=json '{'
'"remote_addr":"$remote_addr",'
'"remote_user":"$remote_user",'
'"time_local":"$time_local",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent",'
'"request_time":$request_time'
'}';
access_log /var/log/nginx/access.json json_combined;
}
适用场景:使用日志分析工具的大规模生产环境,需高效存储、检索和可视化日志的场景。
access_log off关闭访问日志,减少磁盘IO。location ~* \.(jpg|jpeg|png|gif|css|js)$ {
access_log off;
expires 30d;
}
debug/info/notice/warn/error/crit/alert/emerg)。生产环境建议用error(记录错误及以上级别),调试环境用debug(记录详细调试信息),避免过多无用日志影响性能。error_log /var/log/nginx/error.log error; # 生产环境
error_log /var/log/nginx/error.log debug; # 调试环境
适用场景:优化性能或聚焦关键问题的场景。
$request_time、$upstream_response_time)有助于分析,但会增加磁盘IO和存储成本。生产环境建议根据需求选择必要字段,避免过度记录。map指令过滤或使用log_escape函数转义。logrotate定期分割日志(如每天分割、保留7天、压缩旧日志),防止日志文件过大占用磁盘空间。/etc/logrotate.d/nginx):/var/log/nginx/*.log {
daily
missingok
rotate 7
compress
notifempty
create 0640 www-data adm
}