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

如何用Telegraf正则处理器提取连接数、上下行流量及小数数值?

Telegraf Regex Processor 配置:提取日志中的连接数及流量数值

日志样例

2022/11/16 22:38:48 In the last 1h0m0s, there were 10 connections. Traffic Relayed ↑ 60 MB, ↓ 4 MB.

需要提取的核心数值(支持小数格式,如10.5、60.2等):

  • connections: 日志中的连接数
  • upstream: 上行流量数值
  • downstream: 下行流量数值

问题根源

之前配置生成的upstream字段为日志截断版本,核心原因是正则未正确捕获目标数值分组,或处理器配置未将分组值映射到指定字段。

正确配置方案

1. 正则表达式编写

使用分组精准捕获目标数值,同时兼容整数和小数格式:

there were (\d+\.?\d*) connections\. Traffic Relayed ↑ (\d+\.?\d*) MB, ↓ (\d+\.?\d*) MB\.
  • (\d+\.?\d*): 匹配整数或小数,\d+匹配至少1位数字,\.?表示可选小数点,\d*匹配可选的小数部分
  • 转义\.:避免正则中.作为通配符匹配任意字符,确保精准匹配日志中的点号

2. Telegraf 完整配置

以下配置将提取的数值作为**字段(field)**存储(若需作为标签(tag),将[[processors.regex.fields.field]]替换为[[processors.regex.fields.tag]]):

[[processors.regex]]
  # 仅对指定输入插件的指标生效,替换为你的输入名称(如tail、syslog)
  namepass = ["your_input_plugin"]

  [[processors.regex.fields]]
    # 日志内容所在的字段,通常为message
    key = "message"
    pattern = 'there were (\d+\.?\d*) connections\. Traffic Relayed ↑ (\d+\.?\d*) MB, ↓ (\d+\.?\d*) MB\.'
    # 可选:清空原message字段,若需保留则设为"${0}"
    replace = ""

    # 提取connections数值
    [[processors.regex.fields.field]]
      key = "connections"
      value = "${1}"
      # 指定为float类型,支持小数存储
      type = "float"

    # 提取upstream流量数值
    [[processors.regex.fields.field]]
      key = "upstream"
      value = "${2}"
      type = "float"

    # 提取downstream流量数值
    [[processors.regex.fields.field]]
      key = "downstream"
      value = "${3}"
      type = "float"

关键配置说明

  • namepass:限制处理器仅作用于目标输入插件,避免全局干扰其他指标
  • type = "float":将捕获的字符串转换为数值类型,确保后续存储、分析时能正确识别为数值
  • 分组映射:${1}``${2}``${3}需与正则中的分组顺序严格对应,分别对应connections、upstream、downstream

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:06:10