Nginx 日志格式配置:将 JSON 格式日志转换为 GoAccess 可读格式

本文将介绍如何配置 Nginx 日志格式,将 JSON 格式日志转换为 GoAccess 可识别的格式。

Nginx 日志格式配置:

log_format json '{"@timestamp":"$time_iso8601",' 
                      '"host":"$server_addr",' 
                      '"clientip":"$remote_addr",' 
                      '"remote_user":"$remote_user",' 
                      '"request":"$request",' 
                      '"http_user_agent":"$http_user_agent",' 
                      '"size":$body_bytes_sent,' 
                      '"responsetime":$request_time,' 
                      '"uct":"$upstream_connect_time",' 
                      '"uht":"$upstream_header_time",' 
                      '"upstreamtime":"$upstream_response_time",' 
                      '"upstreamhost":"$upstream_addr",' 
                      '"http_host":"$host",' 
                      '"url":"$uri",' 
                      '"domain":"$host",' 
                      '"xff":"$http_x_forwarded_for",' 
                      '"referer":"$http_referer",' 
                      '"status":"$status"}';

GoAccess 日志格式配置:

date-format %Y-%m-%dT%H:%M:%S
log-format %^json{"@timestamp":"%^date-format %^time%^tz","host":"%^s","clientip":"%^h","remote_user":"%^u","request":"%r","http_user_agent":"%^a","size":%b,"responsetime":%T,"uct":"%^{upstream_connect_time}T","uht":"%^{upstream_header_time}T","upstreamtime":"%^{upstream_response_time}T","upstreamhost":"%^{upstream_addr}T","http_host":"%v","url":"%U","domain":"%v","xff":"%^{X-Forwarded-For}i","referer":"%^{Referer}i","status":%s}json$

说明:

  • Nginx 的 log_format 指令定义了 JSON 格式的日志输出。
  • GoAccess 的 log-format 指令将 Nginx 输出的 JSON 格式日志转换为 GoAccess 可识别的格式。
  • date-format 指令用于定义日期格式。
  • %^json 分别表示 GoAccess 的开始和结束标记。
  • %^date-format %^time%^tz 用于将 Nginx 日志中的 @timestamp 字段转换为 GoAccess 可识别的日期时间格式。
  • %^s%^h%r 等表示 GoAccess 的日志字段,对应 Nginx 日志中的相应字段。

使用示例:

假设 Nginx 日志文件名为 access.log,您可以使用以下命令将日志解析到 GoAccess:

goaccess -f access.log -a -d -p -o report.html

注意:

  • 请根据实际情况修改 Nginx 日志格式和 GoAccess 日志格式配置。
  • 确保 GoAccess 版本支持 JSON 格式日志解析。
  • 可以根据需要添加或修改 GoAccess 日志字段。

原文地址: https://www.cveoy.top/t/topic/nGh7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录