You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Grafana展示从Loki日志提取的数值生成折线图

解决Loki日志提取数值并生成折线图的问题

1. 修正Pattern匹配规则

你的日志行格式是[时间] [进程ID]: INFO SEND: Sending 235 emails…,但当前pattern里写的是INFO: GMAIL_SEND:,和日志实际内容不匹配,这会直接导致cnt提取失败。修正后的pattern要严格对应日志结构:

{filename="/var/log/php/error_cli.log"} |~ "INFO SEND: Sending \\d+" 
| pattern "<timestamp> <pid>: INFO SEND: Sending <cnt> emails…"

用<timestamp>和<pid>明确匹配前序字段,确保cnt能精准抓取到数字部分。

2. 将提取的字符串转为数值

提取出的cnt默认是字符串类型,无法直接用于图表数值展示,必须用to_number()函数转换为数值类型:

{filename="/var/log/php/error_cli.log"} |~ "INFO SEND: Sending \\d+" 
| pattern "<timestamp> <pid>: INFO SEND: Sending <cnt> emails…"
| cnt = to_number(cnt)

3. 折线图展示配置

在Grafana中使用上述查询时:

  • 选择折线图面板
  • X轴自动绑定日志的时间戳(无需额外配置)
  • Y轴选择cnt字段作为数值来源
  • 因为每条日志对应一个时间点的独立数值,不需要做任何聚合操作(比如sum、avg),直接展示原始数值即可。如果同一时间区间内有多条日志,可根据需求用last()或first()保留单个值,你的日志是每分钟一条,通常不会出现这种冲突。

验证提取结果的方法

可以先运行以下查询,验证cnt是否正确提取:

{filename="/var/log/php/error_cli.log"} |~ "INFO SEND: Sending \\d+" 
| pattern "<timestamp> <pid>: INFO SEND: Sending <cnt> emails…"
| line_format "{{.cnt}}"

如果返回结果是235、220、442这类纯数字,说明提取成功。

内容的提问来源于stack exchange,提问作者Dude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:07:47