查询日志
Prometheus 自 2.16.0 版本起具备记录引擎执行的所有查询到日志文件的功能。本文档演示了如何使用这个日志文件、其包含的字段以及提供高级技巧来操作日志文件。
启用查询日志
查询日志可以在运行时切换。因此,当你想要调查 Prometheus 实例上的缓慢或高负载故障时,可以启用它。
要启用或禁用查询日志,需要两个步骤:
- 修改配置以添加或移除查询日志配置。
- 重新加载 Prometheus 服务器配置。
将所有查询记录到文件中
以下示例展示了如何将所有查询记录到名为/prometheus/query.log
的文件中。我们假设/prometheus
是数据目录,并且 Prometheus 具有对此目录的写入权限。
首先,修改 prometheus.yml
配置文件:
global: scrape_interval: 15s evaluation_interval: 15s query_log_file: /prometheus/query.logscrape_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 gaugeprometheus_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 counterprometheus_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 自身不会轮转(rotate)查询日志。相反,你可以使用外部工具进行轮转。
logrotate 一个轮转工具,它默认在大多数 Linux 发行版上默认启用。
以下是在/etc/logrotate.d/prometheus
中添加的一个示例文件:
/prometheus/query.log { daily rotate 7 compress delaycompress postrotate killall -HUP prometheus endscript}
这将每天轮转你的日志文件并保持一周的历史记录。
该文档基于 Prometheus 官方文档翻译而成。