nginx日志格式解读指南

271
2025/3/9 9:32:32
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Nginx的日志格式可以通过配置文件 log_format 定义,并且可以通过 access_log 指令来指定日志文件的存放路径、格式和缓存大小。以下是Nginx日志格式的详细解读:

默认日志格式

log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';
  • $remote_addr:记录客户端IP地址。
  • $remote_user:记录客户端用户名称,如果网站未加密则显示“-”。
  • $time_local:记录访问时间和时区,如 18/Jul/2012:17:00:01 +0800
  • $request:记录客户端请求的URL和HTTP协议,如 "GET /index.html HTTP/1.1"
  • $status:记录HTTP请求状态码,如 200
  • $body_bytes_sent:记录发送给客户端的字节数,不包括响应头的大小。
  • $http_referer:记录请求来源页面。
  • $http_user_agent:记录客户端浏览器信息。
  • $http_x_forwarded_for:记录客户端的真实IP地址,通常在反向代理时使用。

自定义日志格式示例

log_format custom '$server_name $remote_addr - $remote_user [$time_local] "$request" ' '$status $upstream_status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for" ''$ssl_protocol $ssl_cipher $upstream_addr $request_time $upstream_response_time';
  • $server_name:虚拟主机名称。
  • $ssl_protocol:SSL协议版本。
  • $ssl_cipher:交换数据中的算法。

日志配置示例

http {
    log_format custom;
    access_log /var/log/nginx/access.log custom;
}

日志切割

Nginx 日志可以通过 logrotate 进行切割,配置文件通常位于 /etc/logrotate.d/ 目录下。

希望以上信息能帮助您更好地理解和分析Nginx日志。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: linux中bash命令支持哪些语法