nginx需输出标准json日志,logstash用json codec解析,es预置模板定义字段类型,kibana索引模式指定@timestamp为时间字段;三者格式对齐才能避免字段丢失或时间错乱。

关键在于让 Nginx 输出可直接解析的结构化日志,再由 Logstash 无损读取、Elasticsearch 正确建模、Kibana 准确识别时间字段——三者格式必须对齐,否则字段丢失或时间错乱。
一、Nginx 端:定义标准 JSON 日志格式
在 /etc/nginx/nginx.conf 的 http 块内添加如下配置:
- 使用双引号包裹键名和字符串值,数值字段不加引号(如
$body_bytes_sent) - 确保
@timestamp字段存在且为 ISO8601 格式($time_iso8601),这是 Kibana 时间筛选的基础 - 避免字段名含点号(如
http.user_agent),改用下划线(http_user_agent)防止 ES 映射异常
示例:
log_format json_log '{"@timestamp":"$time_iso8601",\
"clientip":"$remote_addr",\
"method":"$request_method",\
"url":"$request_uri",\
"status":$status,\
"size":$body_bytes_sent,\
"responsetime":$request_time,\
"agent":"$http_user_agent",\
"referer":"$http_referer"}';
然后在 server 或 location 块中启用:access_log /var/log/nginx/access.log json_log;
二、Logstash 端:用 json codec 直接解析,不依赖 grok
Logstash 配置文件(如 /etc/logstash/conf.d/nginx.conf)中只需三段:
-
input:用
file插件监听日志路径,设start_position => "end"避免重读旧日志,加sincedb_path持久化偏移 -
filter:仅需一行
json { source => "message" },前提是 Nginx 日志每行都是合法 JSON -
output:发往 Elasticsearch,index 名建议用时间动态生成,如
"nginx-%{+YYYY.MM.dd}"
无需 grok、date 过滤器——因为 @timestamp 已由 Nginx 写入,Logstash 只需透传;若仍用默认文本格式,才需 grok + date 补救。
三、Elasticsearch 和 Kibana 端:索引模板与索引模式对齐
提前在 Elasticsearch 中预置索引模板(template),明确字段类型(如 responsetime 设为 float,status 设为 keyword),避免动态映射出错。
Kibana 中创建索引模式时:
- 匹配模式填
nginx-* - 时间字段选
@timestamp(不是time_local或其他别名) - 确认字段列表里已出现
clientip、status、responsetime等,说明解析成功
四、验证是否生效的三个检查点
每改一处,都应快速验证:
- 查 Nginx 日志文件:执行
tail -1 /var/log/nginx/access.log,确认输出是单行 JSON,无换行或乱码 - 查 Logstash 日志:启动时无
json parse error,运行后看 ES 中文档数是否增长 - 查 Kibana Discover:能按
status:200筛选,能对responsetime做直方图统计











