ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

Telegraf Regex 处理器完整指南:用正则批量转换与重命名指标数据

Telegraf Regex 处理器完整指南:用正则批量转换与重命名指标数据 Telegraf Regex 处理器完整指南用正则批量转换与重命名指标数据【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegrafTelegraf 的regex处理器processor允许你使用正则表达式对指标的 tag 值、field 值以及 tag 名、field 名、指标名measurement进行转换与重命名支持捕获组、命名组和批量处理。本文以仓库中 plugins/processors/regex/README.md 为主线结合 regex.go 与 converter.go 的源码实现与 regex_test.go 的测试用例完整讲解该处理器的配置参数、工作原理与实战用法读完后你可以直接在 Telegraf 管线中落地基于正则的数据清洗、脱敏和字段重组。一、功能概述与适用场景regex处理器是一个通用的数据转换插件核心能力可概括为四类tag 值 / field 值转换按正则匹配值并用替换表达式改写也支持通过命名组一次批量生成多个新 tag / fieldtag 重命名 / field 重命名基于正则匹配 tag 名 / field 名将其重命名为新名称指标名measurement重命名基于正则匹配指标名并重命名。它最典型的应用场景包括把resp_code200归一化为resp_code2xx以方便聚合、从request/api/search/...这类 URL 字段中抽取method、category等子维度、去掉字段名上的前缀如client_ip→ip、以及把nginx_requests这类带后缀的指标名收敛为nginx。该插件在仓库中注册名称为regex见 regex.go 中的processors.Add(regex, ...)自 Telegraf v1.7.0 起引入类型标注为 transformation适用于所有平台。⚠️重要限制regex处理器只对字符串类型的 field 生效。整数、浮点数、布尔值等其他数据类型的 field 会被直接跳过详见下文源码分析。二、全局配置选项与所有 Telegraf 插件一样regex处理器也支持各类全局配置设置用于修饰指标、tag、field、创建别名alias以及配置插件执行顺序。这些内容统一收录在 docs/CONFIGURATION.md#plugins 中包括但不限于指标过滤类namepass、namedrop、pass、drop、tagpass、tagdrop、tagexclude、taginclude、fieldpass、fielddrop等namepass_separator等参数用于配置过滤表达式的分隔符alias与order等处理器通用设置。在本文所有示例中出现的namepass [nginx_requests]就属于这类全局配置其作用是只让指标名为nginx_requests的指标进入处理器避免影响其他指标。三、配置参数详解一份完整的示例配置见 sample.conf它同时也是插件通过go:embed内置的默认示例见 regex.go。regex处理器由五类可重复的配置小节组成它们可以同时配置多个且全部会被依次应用# Transforms tag and field values as well as measurement, tag and field names with regex pattern [[processors.regex]] namepass [nginx_requests] ## Tag value conversion(s). Multiple instances are allowed. [[processors.regex.tags]] ## Tag(s) to process with optional glob expressions such as *. key resp_code ## Regular expression to match the tag value. If the value doesnt ## match the tag is ignored. pattern ^(\\d)\\d\\d$ ## Replacement expression defining the value of the target tag. You can ## use regexp groups or named groups e.g. ${1} references the first group. replacement ${1}xx ## Name of the target tag defaulting to key if not specified. ## In case of wildcards being used in key the currently processed ## tag-name is used as target. # result_key method ## Appends the replacement to the target tag instead of overwriting it when ## set to true. # append false ## Field value conversion(s). Multiple instances are allowed. [[processors.regex.fields]] ## Field(s) to process with optional glob expressions such as *. key request ## Regular expression to match the field value. If the value doesnt ## match or the field doesnt contain a string the field is ignored. pattern ^/api(?Pmethod/[\\w/])\\S* ## Replacement expression defining the value of the target field. You can ## use regexp groups or named groups e.g. ${method} references the group ## named method. replacement ${method} ## Name of the target field defaulting to key if not specified. ## In case of wildcards being used in key the currently processed ## field-name is used as target. # result_key method ## Rename metric fields [[processors.regex.field_rename]] ## Regular expression to match on the field name pattern ^search_(\\w)d$ ## Replacement expression defining the name of the new field replacement ${1} ## If the new field name already exists, you can either overwrite the ## existing one with the value of the renamed field OR you can keep ## both the existing and source field. # result_key keep ## Rename metric tags [[processors.regex.tag_rename]] ## Regular expression to match on a tag name pattern ^search_(\\w)d$ ## Replacement expression defining the name of the new tag replacement ${1} ## If the new tag name already exists, you can either overwrite the ## existing one with the value of the renamed tag OR you can keep ## both the existing and source tag. # result_key keep ## Rename metrics [[processors.regex.metric_rename]] ## Regular expression to match on an metric name pattern ^search_(\\w)d$ ## Replacement expression defining the new name of the metric replacement ${1}3.1 tags 与 fields 小节值转换这两个小节用于转换 tag / field 的值每个小节支持以下参数参数必填说明key是要处理的 tag / field 名称支持 glob 表达式如*。对于tags/fields小节这是唯一必填参数缺少时会报key required错误见 converter.gopattern是匹配 tag / field 值的正则表达式。若值不匹配则跳过该 tag / field 不处理replacement视情况替换表达式定义目标 tag / field 的新值。可使用捕获组如${1}引用第 1 组或命名组如${mygroup}引用名为mygroup的组result_key否目标 tag / field 的名称不指定时默认为key即原地覆盖。若key中使用了通配符则以当前实际处理的 tag / field 名作为目标名append否仅对tags小节有效。设为true时将replacement的结果追加到目标 tag 现有值之后而不是覆盖它默认false转换的触发条件见 converter.go 与applyFields的实现只有当 tag / field名称匹配key使用 glob 匹配且其值匹配pattern时才会应用转换对于 field还要求其值必须是string类型。任一条件不满足该指标都不会被转换。注意append的语义细节见 converter.go它是把replacement生成的新值拼接到目标 tag 已有值的后面例如已有 tagverbGET替换结果为 OK时最终值变为GET OK。3.2 field_rename 与 tag_rename 小节名称重命名这两个小节用于对 tag / field 的名称进行批量重命名与tags/fields小节的“值转换”在语义上不同。参数如下参数说明pattern匹配 tag / field 名称的正则表达式replacement替换表达式定义新名称result_key可选取值overwrite或keep默认keep用于控制新名称与已有名称冲突时的行为冲突处理规则overwrite用源 tag / field 覆盖已存在的目标 tag / field且源 tag / field 无论如何都会被移除keep默认当目标名称已存在时目标与源 tag / field 都保持不变不进行重命名。需要指出的是在这两个小节中配置key是无效的——插件在Init()阶段会打印日志提示tag_rename/field_rename section contains a key which is ignored during processing见 regex.go。另外从源码看若result_key填了非法值非overwrite/keep/空Init()会返回错误invalid metrics result_key见 converter.go。重命名实现上有一个值得了解的细节见 converter.go当目标名已存在且为overwrite模式时替换操作会被延迟到遍历结束之后统一执行因为不能在遍历 tag / field 列表的同时修改它否则会引发内存访问问题源码注释明确指出这会导致 invalid memory dereference panic。3.3 metric_rename 小节指标名重命名与 tag / field 重命名类似metric_rename用于重命名匹配pattern的指标名新名称由replacement指定。与名称重命名小节不同只要指标名匹配pattern转换始终被应用没有冲突判断逻辑见 converter.go 中applyMetricRename的实现result_key对指标名重命名无效不应设置。若配置了result_keyInit()会打印日志提示其被忽略见 regex.go。四、命名组批量处理Batch Processing这是tags与fields小节特有的高级能力使用命名组在一条转换规则中批量创建多个新 tag 或 field。用法要点pattern中的所有捕获组都必须命名可以使用额外的非捕获组或其他正则表达式此时不能设置replacement和result_key因为新 tag / field 的名称就是命名组的组名值就是该组匹配到的内容。从源码实现看这一模式由setup()自动探测见 converter.go当ResultKey与Replacement均为空时插件检查regexp.SubexpNames()返回的组名列表若所有组都有名字则进入“named-group 模式”否则打印警告并退回显式空替换模式。进入命名组模式后实际处理逻辑为见 converter.go 与applyFields对应分支对每个匹配的 tag / field取出各命名组的匹配内容逐个以组名为 key 新增 tag / field空匹配的组会被跳过。五、实战示例从一条 Nginx 访问日志指标说起以下示例均基于仓库文档中的同一条输入指标line protocol 格式nginx_requests,verbGET,resp_code200 request/api/search/?categorypluginsqregexsortasc,referrer-,ident-,http_version1.1,agentUserAgent,client_ip127.0.0.1,auth-,resp_bytes270i 1519652321000000000其结构为指标名nginx_requeststags 为verbGET、resp_code200fields 包含requestURL 字符串、client_ip、resp_bytes整数 270等。5.1 显式指定Explicit specification[[processors.regex]] namepass [nginx_requests] [[processors.regex.tags]] key resp_code pattern ^(\\d)\\d\\d$ replacement ${1}xx [[processors.regex.fields]] key request pattern ^/api(?Pmethod/[\\w/])\\S* replacement ${method} result_key method [[processors.regex.fields]] key request pattern .*category(\\w).* replacement ${1} result_key search_category [[processors.regex.field_rename]] pattern ^client_(\\w)$ replacement ${1}转换结果-nginx_requests,verbGET,resp_code200 request/api/search/?categorypluginsqregexsortasc,referrer-,ident-,http_version1.1,agentUserAgent,client_ip127.0.0.1,auth-,resp_bytes270i 1519652321000000000 nginx_requests,verbGET,resp_code2xx request/api/search/?categorypluginsqregexsortasc,method/search/,categoryplugins,referrer-,ident-,http_version1.1,agentUserAgent,ip127.0.0.1,auth-,resp_bytes270i 1519652321000000000可以看到四个转换依次生效tagresp_code被改写为2xxfieldrequest的命名组method被抽取为新的 fieldmethod第二个fields规则从 query 参数中抽取出categoryplugins作为新 field最后field_rename将client_ip重命名为ip。注意resp_bytes270i是整数完全不受影响。5.2 追加模式Appending[[processors.regex]] namepass [nginx_requests] [[processors.regex.tags]] key resp_code pattern ^2\d\d$ replacement OK result_key verb append true转换结果-nginx_requests,verbGET,resp_code200 request/api/search/?categorypluginsqregexsortasc,referrer-,ident-,http_version1.1,agentUserAgent,client_ip127.0.0.1,auth-,resp_bytes270i 1519652321000000000 nginx_requests,verbGET\ OK,resp_code200 request/api/search/?categorypluginsqregexsortasc,referrer-,ident-,http_version1.1,agentUserAgent,client_ip127.0.0.1,auth-,resp_bytes270i 1519652321000000000这里把 resp_code 的匹配结果 OK追加到已有 tagverb的GET之后得到GET\ OK。5.3 命名组批量抽取Named groups[[processors.regex]] namepass [nginx_requests] [[processors.regex.fields]] key request pattern ^/api/(?Pmethod\w)[/?].*category(?Pcategory\w)(?:.*)转换结果-nginx_requests,verbGET,resp_code200 request/api/search/?categorypluginsqregexsortasc,referrer-,ident-,http_version1.1,agentUserAgent,client_ip127.0.0.1,auth-,resp_bytes270i 1519652321000000000 nginx_requests,verbGET,resp_code200 request/api/search/?categorypluginsqregexsortasc,methodsearch,categoryplugins,referrer-,ident-,http_version1.1,agentUserAgent,client_ip127.0.0.1,auth-,resp_bytes270i 1519652321000000000只配置了key和pattern没有replacement/result_key。由于两个捕获组method与category均被命名插件自动进入批量模式一次抽出新 fieldmethodsearch与categoryplugins。5.4 指标名重命名Metric renaming[[processors.regex]] [[processors.regex.metric_rename]] pattern ^(\w)_.*$ replacement ${1}转换结果-nginx_requests,verbGET,resp_code200 request/api/search/?categorypluginsqregexsortasc,referrer-,ident-,http_version1.1,agentUserAgent,client_ip127.0.0.1,auth-,resp_bytes270i 1519652321000000000 nginx,verbGET,resp_code200 request/api/search/?categorypluginsqregexsortasc,referrer-,ident-,http_version1.1,agentUserAgent,client_ip127.0.0.1,auth-,resp_bytes270i 1519652321000000000指标名nginx_requests被改写为nginx其余 tag / field 均保持不变。该规则未使用namepass说明它会对所有流入指标生效因此实践中通常需要配合namepass/namedrop来限定范围。六、源码实现与工作流程6.1 处理顺序从 regex.go 中Apply()的实现可以看出处理器对每条指标按配置顺序依次执行五类转换先全部tags再全部fields然后是全部tag_rename、field_rename最后是所有metric_rename。这意味着后配置的tags规则可以看到前面规则产生的新 tag同一小节内的多条规则之间存在先后依赖关系可以像流水线一样串联仓库测试 TestMultipleConversions 就验证了resp_code→resp_code_group→resp_code_text的链式转换。6.2 初始化与错误处理Init()阶段见 regex.go完成以下工作为每个转换器预编译正则表达式regexp.Compile若正则有语法错误Init()直接返回错误并指明出错的小节如tags ...插件将无法启动为tags/fields小节通过filter.Compile编译key的 glob 过滤器校验result_key取值决定是否进入命名组批量模式。6.3 类型安全与性能applyFields中通过 Go 类型断言value, ok : field.Value.(string)确认 field 值为字符串非字符串直接跳过见 converter.go——这正是文档开头“只操作字符串 field”限制的实现来源正则表达式在Init()时一次性编译、处理时复用避免每条指标重复编译仓库还提供了基准测试 BenchmarkConversions 用于评估转换开销处理器采用跟踪指标感知的写法TestTrackedMetricNotLost 验证了经metric.WithTracking包装的指标在转换并Accept()后投递信息DeliveryInfo不会丢失。6.4 通配符与匹配语义key支持 glob 表达式。当使用*时会匹配指标上所有 tag / field 名由filter.Compile实现配合值正则即可实现“对所有字段做同一类清洗”。仓库测试 TestAnyTagConversion 展示了用key *配合 UUID 正则对所有 tag 做脱敏[0-9a-f]{8}-...→{UUID}TestAnyFieldConversion 则用key *将所有字符串 field 中的四位数字替换为{ID}同时验证了整数 fieldcounter不被触碰。七、与同类处理器及文档的配合使用regex处理器通常与以下配置组合使用以获得最佳效果全局过滤用namepass限定指标范围用tagpass/fieldpass进一步限定 tag / field 范围详见 docs/CONFIGURATION.md#plugins处理器顺序Telegraf 支持通过order配置处理器执行顺序可参考仓库中的处理器排序测试用例 agent/testcases/processor-order-explicit 与 agent/testcases/processor-order-appearance 理解其语义管道协作若需要更复杂的字符串处理如模板化、脚本化逻辑可以结合其他 processor 使用而regex的定位始终是“轻量、高性能、纯正则”的原地转换。八、常见问题与注意事项field 是数字或布尔值为什么不生效因为插件通过类型断言只处理string类型 field数字、布尔等类型会被静默跳过。若确需处理可先在管线中通过其他方式将其转换为字符串。命名组模式下为什么必须给所有捕获组命名因为命名组模式的触发条件要求result_key与replacement均为空且所有捕获组都有名字存在未命名组时会回退到“显式空替换”模式并打印警告行为可能不符合预期。result_key与append的适用性append仅对tags小节有意义metric_rename不支持result_keyfield_rename/tag_rename的result_key只接受overwrite与keep。正则转义TOML 双引号字符串中反斜杠需要转义如^(\\d)\\d\\d$单引号字面量字符串则不需要如^2\d\d$示例中两种写法均出现过。指标被覆盖而非新增tags/fields小节不指定result_key时是原地覆盖值想保留原始值请用result_key输出到新名称。九、相关资源插件说明文档plugins/processors/regex/README.md插件主实现plugins/processors/regex/regex.go转换器与匹配逻辑实现plugins/processors/regex/converter.go完整示例配置plugins/processors/regex/sample.conf单元测试与基准测试plugins/processors/regex/regex_test.go全局配置与插件过滤选项docs/CONFIGURATION.md#plugins【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表