使用 Prometheus 查询日志
从 2.16.0 版本开始,Prometheus 能够将引擎运行的所有查询记录到日志文件中。本指南将演示如何使用该日志文件,它包含哪些字段,并提供有关如何操作日志文件的进阶提示。
启用查询日志
查询日志可以在运行时进行切换。因此,当您想要调查 Prometheus 实例上的慢查询或高负载时,可以将其激活。
要启用或禁用查询日志,需要两个步骤
- 修改配置以添加或移除查询日志配置。
- 重新加载 Prometheus 服务器配置。
将所有查询记录到文件
本示例演示如何将所有查询记录到一个名为 /prometheus/query.log
的文件中。我们将假设 /prometheus
是数据目录,并且 Prometheus 对其具有写入权限。
首先,修改 prometheus.yml
配置文件
global:
scrape_interval: 15s
evaluation_interval: 15s
query_log_file: /prometheus/query.log
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
然后,重新加载 Prometheus 配置
$ curl -X POST http://127.0.0.1:9090/-/reload
或者,如果 Prometheus 没有使用 --web.enable-lifecycle
启动,并且您不是在 Windows 上运行,可以通过向 Prometheus 进程发送 SIGHUP 信号来触发重新加载。
文件 /prometheus/query.log
现在应该已存在,并且所有查询都将记录到该文件中。
要禁用查询日志,请重复上述操作,但从配置中移除 query_log_file
。
验证查询日志是否已启用
Prometheus 方便地暴露了指标,用于指示查询日志是否已启用并正常工作
# HELP prometheus_engine_query_log_enabled State of the query log.
# TYPE prometheus_engine_query_log_enabled gauge
prometheus_engine_query_log_enabled 0
# HELP prometheus_engine_query_log_failures_total The number of query log failures.
# TYPE prometheus_engine_query_log_failures_total counter
prometheus_engine_query_log_failures_total 0
第一个指标 prometheus_engine_query_log_enabled
在查询日志启用时设置为 1,否则为 0。第二个指标 prometheus_engine_query_log_failures_total
表示未能记录的查询数量。
查询日志格式
查询日志是 JSON 格式的日志。以下是查询中存在的字段概述
{
"params": {
"end": "2020-02-08T14:59:50.368Z",
"query": "up == 0",
"start": "2020-02-08T13:59:50.368Z",
"step": 5
},
"stats": {
"timings": {
"evalTotalTime": 0.000447452,
"execQueueTime": 7.599e-06,
"execTotalTime": 0.000461232,
"innerEvalTime": 0.000427033,
"queryPreparationTime": 1.4177e-05,
"resultSortTime": 6.48e-07
}
},
"ts": "2020-02-08T14:59:50.387Z"
}
params
:查询。包括开始和结束时间戳、步长以及实际的查询语句。stats
:统计信息。目前包含内部引擎计时器。ts
:查询结束时的时间戳。
此外,根据触发请求的原因,JSON 行中还会包含其他字段。
API 查询和控制台
HTTP 请求包含客户端 IP、方法和路径
{
"httpRequest": {
"clientIP": "127.0.0.1",
"method": "GET",
"path": "/api/v1/query_range"
}
}
如果设置了 Web 前缀,路径将包含该前缀,并且还可以指向一个控制台。
客户端 IP 是网络 IP 地址,不考虑 X-Forwarded-For
等头部。如果您希望记录代理背后的原始调用者,则需要在代理本身中进行操作。
记录规则和告警
记录规则和告警包含一个 ruleGroup
元素,其中包含文件的路径和组的名称
{
"ruleGroup": {
"file": "rules.yml",
"name": "partners"
}
}
轮换查询日志
Prometheus 不会自行轮换查询日志。相反,您可以使用外部工具来完成此操作。
其中一个工具是 logrotate。它在大多数 Linux 发行版中默认启用。
以下是您可以作为 /etc/logrotate.d/prometheus
添加的文件示例
/prometheus/query.log {
daily
rotate 7
compress
delaycompress
postrotate
killall -HUP prometheus
endscript
}
这将每天轮换您的文件并保留一周的历史记录。