Nginx日志需通过Promtail采集JSON格式日志并打标后发送至Loki,再在Grafana中用LogQL查询并与Prometheus指标联动;关键在于日志JSON化、标签对齐、时间戳一致。

要实现 Nginx 日志与 Grafana Loki 的统一搜索和关联分析,核心不是让 Nginx 直接对接 Loki(它不支持),而是通过日志采集器(如 Promtail)把 Nginx 的结构化日志发送到 Loki,再在 Grafana 中用 LogQL 查询,并与 Prometheus 指标联动。关键在于日志格式统一、标签对齐、时间戳一致。
1. 规范 Nginx 日志格式,输出 JSON
Nginx 默认 access_log 是纯文本,Loki 虽能解析,但结构化查询和字段提取效率低。推荐改用 JSON 格式,便于 Promtail 提取 label 和内容:
log_format json_logs '{'
'"time": "$time_iso8601",'
'"remote_addr": "$remote_addr",'
'"host": "$host",'
'"request": "$request",'
'"status": "$status",'
'"body_bytes_sent": "$body_bytes_sent",'
'"http_referer": "$http_referer",'
'"http_user_agent": "$http_user_agent",'
'"request_time": "$request_time",'
'"upstream_response_time": "$upstream_response_time",'
'"upstream_addr": "$upstream_addr"'
'}';然后在 server 或 http 块中启用:
access_log /var/log/nginx/access.json json_logs;
确保日志目录可写,重启 Nginx 生效。
2. 配置 Promtail 抓取并打标
Promtail 是 Loki 官方推荐的 agent,负责读取日志文件、添加静态/动态标签、转发到 Loki。需重点配置:
-
job_name:设为
nginx,方便后续过滤 -
static_labels:补充环境信息,如
{job="nginx", cluster="prod", app="web"} - pipeline_stages:解析 JSON 并提取关键字段作为 labels(用于 LogQL 过滤)
scrape_configs:
- job_name: nginx
static_configs:
- targets:
- localhost
labels:
job: nginx
cluster: prod
app: web
pipeline_stages:
- docker: {}
- json:
expressions:
time: time
status: status
host: host
request: request
request_time: request_time
- labels:
status:
host:
request:
- timestamp:
source: time
format: RFC3339Nano注意:format: RFC3339Nano 必须与 Nginx $time_iso8601 格式兼容(形如 2024-05-20T14:23:18.123Z)。Promtail 启动后会自动 tail JSON 日志文件。
3. 在 Grafana 中关联日志与指标
Grafana 支持在 Metrics(Prometheus)面板中点击“Explore logs”跳转到对应时间范围的 Loki 日志;也支持在 Logs(Loki)视图中用 | line_format 或 | unwrap 关联指标。常用技巧:
- 在 Prometheus 查询中加
__error__或__name__标签,再右键 “View logs in Loki” —— 自动带入时间+labels - 在 Loki LogQL 中用
| json | __error__ = "500"筛选错误,再加| line_format "{{.request}} {{.status}}"美化输出 - 用
rate({job="nginx"} |~ "50[0-9]" [1h])计算每小时 5xx 出现频率,与 Prometheus 的rate(nginx_http_requests_total{code=~"5.."}[1h])对比验证一致性
若 Nginx 指标已通过 nginx-exporter 或 nginx-prometheus-exporter 暴露给 Prometheus,则指标与日志的 job、instance、cluster 标签保持一致,就能自然联动。
4. 补充建议:提升可查性与稳定性
- 在 Nginx 中增加唯一请求 ID(如
$request_id),并在日志 JSON 中输出,方便跨服务追踪 - 为 Promtail 配置
relabel_configs动态提取 host、path,避免硬编码 - Loki 查询时加
| __error__ = ""排除解析失败日志,防止干扰 - 定期 rotate Nginx JSON 日志(logrotate +
copytruncate),避免 Promtail 丢失 offset
不复杂但容易忽略:时间戳精度、标签命名一致性、JSON 字段空值处理(Promtail 默认跳过缺失字段,可用 json { optional: true } 控制)。做好这三点,Nginx 日志就能真正融入可观测体系,实现指标驱动日志下钻、日志反查指标波动根源。


















