要通过 Prometheus 的 NGINX Exporter 来抓取 NGINX 中的日志信息,例如状态码为 4xx 或 5xx 的日志,需要结合以下几种工具和方法:
1. NGINX Exporter 基础功能
NGINX Exporter 是一个 Prometheus Exporter,用于从 NGINX 的 /status
端点收集指标数据,但它本身并不直接处理日志文件。因此,若要监控 NGINX 中状态码为 4xx 或 5xx 的日志信息,需要额外的步骤。
2. 使用 logstash
或 fluentd
收集 NGINX 日志
为了从 NGINX 的日志文件中提取特定信息,并将其转换为 Prometheus 能够抓取的指标,我们可以使用 logstash
或 fluentd
等日志收集工具。
使用 fluentd
示例
- 安装 Fluentd 和 Prometheus 插件首先,需要安装 Fluentd 和相关的插件,确保 Fluentd 可以从日志中提取数据并以 Prometheus 格式暴露出来:
gem install fluentd
gem install fluent-plugin-prometheus
- 配置 Fluentd配置 Fluentd,解析 NGINX 日志并生成 Prometheus 格式的指标。创建一个 Fluentd 配置文件
fluent.conf
,内容如下:
<source>
@type tail
path /var/log/nginx/access.log
pos_file /var/log/td-agent/nginx-access.log.pos
tag nginx.access
<parse>
@type nginx
</parse>
</source>
<filter nginx.access>
@type grep
<regexp>
key status
pattern ^4|5[0-9][0-9]$
</regexp>
</filter>
<match nginx.access>
@type prometheus
<metric>
name nginx_http_status_total
type counter
desc Nginx HTTP status code counter
keys status
<labels>
status ${status}
</labels>
</metric>
<metric>
name nginx_http_request_bytes_total
type counter
desc Total bytes received by the Nginx server
key bytes
</metric>
</match>
<source>
@type prometheus_monitor
<labels>
tag nginx.access
</labels>
</source>
<source>
@type prometheus_output_monitor
<labels>
tag nginx.access
</labels>
</source>
<match **>
@type stdout
</match>
- **Source**:读取 `/var/log/nginx/access.log` 文件,并解析日志。
- **Filter**:通过正则表达式过滤状态码为 4xx 或 5xx 的日志。
- **Match**:将解析后的日志信息转化为 Prometheus 格式的指标。
- **Prometheus 输出**:启动一个 HTTP 端点,供 Prometheus 抓取这些指标。
- 启动 Fluentd运行 Fluentd,应用配置文件:
fluentd -c /path/to/fluent.conf
Fluentd 会启动一个监听端口,默认是 http://localhost:24231/metrics
,以 Prometheus 格式暴露解析后的日志数据。
3. 配置 Prometheus 抓取 Fluentd 暴露的指标
在 Prometheus 的配置文件 prometheus.yml
中,添加 Fluentd 作为新的抓取目标:
scrape_configs:
- job_name: 'nginx_logs'
static_configs:
- targets: ['localhost:24231']
4. 使用 Grafana 可视化
现在 Prometheus 已经可以抓取 NGINX 的 4xx 和 5xx 状态码日志信息,您可以在 Grafana 中创建仪表盘,展示这些信息的时间变化趋势,分析 NGINX 服务的健康状况。
总结
虽然 NGINX Exporter 本身无法直接抓取日志信息,但是结合 Fluentd 等日志收集工具,您可以轻松地将 NGINX 日志中的特定信息(如 4xx 和 5xx 状态码)转化为 Prometheus 可抓取的指标,并最终在 Grafana 中进行可视化。