Telegraf Datadog Output 插件实战:配置详解、指标转换规则与 rate_interval 原理 📅 发布时间:2026/9/14 18:00:09 👁 浏览次数: Telegraf Datadog Output 插件实战配置详解、指标转换规则与 rate_interval 原理【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf本篇围绕 Telegraf 的outputs.datadog插件展开系统讲解如何通过 Datadog Metrics APIv1将 Telegraf 采集的指标写入 Datadog从完整的 TOML 配置项逐一解析apikey、timeout、url、代理、压缩、rate_interval到源码级的指标命名、类型映射与数值转换规则再到rate_interval将 statsd 计数器转换为 rate 的底层实现与测试验证。读完后你可以独立完成该插件的配置、排错并能准确预判每个 Telegraf 字段在 Datadog 侧最终呈现的指标名与指标类型。插件定位面向 Datadog Metrics API v1 的输出插件Datadog Output 插件将 Telegraf 指标写入 Datadog Metrics API前提是持有一个有效的apikey在 Datadog 账户设置中获取。插件文档plugins/outputs/datadog/README.md明确注明了版本适用边界This plugin supports the v1 API.这一限制在源码中同样得到印证。datadog.go 定义了默认写入端点const datadogAPI https://app.datadoghq.com/api/v1/series而在插件注册时init 函数设置了两个关键默认值func init() { outputs.Add(datadog, func() telegraf.Output { return Datadog{ URL: datadogAPI, Compression: none, } }) }即默认请求https://app.datadoghq.com/api/v1/series默认不做压缩。认证方式是把apikey作为查询参数拼在 URL 上见下文“认证机制”一节这也是文档注释中“由于认证方式限制目前只支持 v1 API”的原因。完整配置项详解以下为插件的官方示例配置完整保留自 sample.conf# Configuration for DataDog API to send metrics to. [[outputs.datadog]] ## Datadog API key apikey my-secret-key ## Connection timeout. # timeout 5s ## Write URL override; useful for debugging. ## This plugin only supports the v1 API currently due to the authentication ## method used. # url https://app.datadoghq.com/api/v1/series ## Set http_proxy # use_system_proxy false # http_proxy_url http://localhost:8888 ## Override the default (none) compression used to send data. ## Supports: zlib, none # compression none ## When non-zero, converts count metrics submitted by inputs.statsd ## into rate, while dividing the metric value by this number. ## Note that in order for metrics to be submitted simultaneously alongside ## a Datadog agent, rate_interval has to match the interval used by the ## agent - which defaults to 10s # rate_interval 0s下面逐项说明各配置的含义、默认值与源码中的作用位置对应 Datadog 结构体 中的字段apikey必填Datadog 的 API 密钥是唯一的强制配置。Connect 方法 在插件启动连接时会做显式校验func (d *Datadog) Connect() error { if d.Apikey { return errors.New(apikey is a required field for datadog output) } ... }未配置apikey时插件会直接报错不会静默启动。timeout连接超时TOML 时长格式如5s。它对应config.Duration类型定义见 config/types.go解析时兼容整数秒、浮点秒以及3s这类时长字符串。Connect时它被设为http.Client的Timeout控制单次写请求的最大耗时。url调试用 URL 覆盖默认指向https://app.datadoghq.com/api/v1/series可覆盖为任意地址典型用途是把请求打到本地 mock 服务做调试。测试 TestUriOverride 正是利用httptest.NewServer起了一个本地假服务把url指向它来验证覆盖生效、请求能成功发出并收到 200。代理配置use_system_proxy / http_proxy_url这两个选项来自 Telegraf 公共代理组件 plugins/common/proxy/proxy.go其HTTPProxy结构体被内嵌进Datadoguse_system_proxy true使用环境变量http.ProxyFromEnvironment即HTTP_PROXY/HTTPS_PROXY等http_proxy_url显式指定代理地址会做 URL 解析校验非法地址在Connect阶段报错两者都不设置时不走代理。compressionzlib 或 none覆盖默认none的压缩方式仅支持zlib与none两个取值。Write 方法 中的处理逻辑compression zlib通过 internal/content_coding.go 的NewContentEncoder创建 zlib 编码器压缩 JSON 负载并设置请求头Content-Encoding: deflatecompression none或任何其他值走default分支直接发送原始 JSON。注意请求的Content-Type始终为application/json压缩只作用于请求体传输编码。TestCompressionOverride 验证了 zlib 模式下请求可被本地服务正常接收。rate_interval把 count 指标转换为 rate这是本插件最有技术含量的一项配置后文专门展开。此外与 Telegraf 其他 output 一样[[outputs.datadog]]还支持全局的插件级过滤配置如namepass/nameprefix/tagpass、字段过滤等详见 docs/CONFIGURATION.md 的 Plugins 章节。数据流与请求格式从 Telegraf Metric 到 Datadog Series理解该插件最快的方式是看它发送给 Datadog 的 JSON 结构。datadog.go 定义了完整的序列化模型type TimeSeries struct { Series []*Metric json:series } type Metric struct { Metric string json:metric Points [1]Point json:points Host string json:host Type string json:type,omitempty Tags []string json:tags,omitempty Interval int64 json:interval } type Point [2]float64即整个批次包成一个{series: [...]}每条Metric只携带一个数据点Point二元数组[时间戳(秒), 值]并带有指标名、host、类型、标签与 interval。Write 方法 的完整流程调用convertToDatadogMetric把整批[]telegraf.Metric转换为[]*Metric若结果为空例如所有字段都是非法值被跳过直接返回 nil不发请求json.Marshal序列化失败则返回unable to marshal TimeSeries错误按compression决定是否 zlib 压缩向authenticatedURL()发起POST校验响应状态码仅200–209视为成功否则读取响应体并返回received bad status code, code: body。TestBadStatusCode 用 500 响应验证了错误信息会携带 Datadog 返回的原始错误 JSON例如{errors: [Something bad happened to the server.]}。认证机制与 API Key 防泄漏apikey不走 Header而是作为查询参数附加在 URL 上func (d *Datadog) authenticatedURL() string { q : url.Values{ api_key: []string{d.Apikey}, } return fmt.Sprintf(%s?%s, d.URL, q.Encode()) }TestAuthenticatedUrl 断言其输出为url?api_keykey。值得注意的是插件对密钥泄漏的防护构造请求失败或发送失败时错误信息中会出现的密钥会被替换为****************redactedAPIKey : **************** ... return fmt.Errorf(unable to create http.Request, %s, strings.ReplaceAll(err.Error(), d.Apikey, redactedAPIKey))这保证即使url或网络错误把带密钥的 URL 带入日志日志里也不会留下明文 key。指标命名规则metric . fieldDatadog 指标名的生成规则与 README 一致实现于 convertToDatadogMetric一般地指标名 Telegraf 指标名 . 字段名例如指标cpu的字段usage_user会变成cpu.usage_user特例字段名恰好是value时不再追加后缀直接使用指标名源码注释adding .value seems redundant here。这与 statsd 输入产生的value字段天然契合。标签tags与 host 的处理所有 Telegraf tag 按key:value格式拼接为 Datadog tags 数组见 buildTags 与 TestBuildTags例如 tagonetwo→one:two名为host的 tag 被单独取出填充到 JSON 的host字段host, _ : m.GetTag(host)它同时也会出现在 tags 中。字段值与指标类型转换规则数值类型转换一切皆 floatDatadog v1 API 只接受浮点数值因此 setValue 负责把 Telegraf 字段值统一转为float64int64/uint64/float64直接转换boolfalse → 0.0true → 1.0其他类型如字符串返回undeterminable field type错误整个指标会被记录日志并跳过Unable to build Metric for %s ... skipping。字符串在更前置的 verifyValue 就被判定为非法func verifyValue(v interface{}) bool { switch v : v.(type) { case string: return false case float64: // The payload will be encoded as JSON, which does not allow NaN or Inf. return !math.IsNaN(v) !math.IsInf(v, 0) } return true }也就是说字符串字段被忽略TestVerifyValue 验证11234.5字符串被判为无效NaN/Inf这类无法用 JSON 表示的浮点值被忽略TestNaNIsSkipped 与 TestInfIsSkipped 验证了仅含此类字段时整个指标不会触发任何网络请求。buildMetrics 逐字段执行“校验 → 转 float → 填充时间戳”时间戳取m.Time().Unix()秒级TestBuildPoint 覆盖了 float、int32/int64、uint64、bool 等各类输入的预期输出。指标类型映射type 字段Datadog 的type与 Telegraf 的 metric type 对应关系在 convertToDatadogMetric 中Telegraf 类型未设置 rate_interval设置 rate_interval 且可 rate 化gaugegaugegauge不转换countercountrate值除以 interval见下untyped空不输出 typerate仅 statsd 的 count 字段其他空空同时interval字段默认1被 rate 化时取rate_interval的秒数源码注释interval is expected to be in seconds。rate_interval 深入与 Datadog Agent 对表的关键配置README 对rate_interval的说明是When non-zero, converts count metrics submitted by inputs.statsd into rate, while dividing the metric value by this number. Note that in order for metrics to be submitted simultaneously alongside a Datadog agent, rate_interval has to match the interval used by the agent - which defaults to 10s其设计目标是让 Telegraf 可以和 Datadog Agent 并存上报同一业务指标的 rate 值Datadog Agent 默认按10s计算 rate。转换逻辑集中在两个函数转换条件——isRateable 依赖inputs.statsd写入的metric_typetag该 tag 由 plugins/inputs/statsd/statsd.go 在解析 statsd 报文时按gauge|set|counter|timing|histogram|distribution设置metric_type counter整个指标可 rate 化metric_type timing或histogram只有名为count的字段可 rate 化mean/median/sum 等统计量字段保持原样其他情况不转换。这正是文档强调“只支持经由inputs.statsd摄入的指标”的原因——没有metric_typetag 就无法判定是否可 rate 化。转换动作datadog.goif d.RateInterval 0 isRateable(statsDMetricType, fieldName) { // interval is expected to be in seconds rateIntervalSeconds : time.Duration(d.RateInterval).Seconds() interval int64(rateIntervalSeconds) dogM[1] dogM[1] / rateIntervalSeconds tname rate }即值除以rate_interval的秒数、interval取该秒数、type置为rate。单元测试 TestNonZeroRateIntervalConvertsRatesToCount 与 TestZeroRateIntervalConvertsRatesToCount 提供了精确的预期值rate_interval 10s时counter 指标value100→10typerate、Interval10metric_typetiming/histogram时count1→0.1且指标名为name.count而lower/mean/median/stddev/sum/upper等字段保持原值、type为空、Interval1rate_interval 0默认时counter 保持typecount、原值100、Interval1timing/histogram 的 count 字段也不转换。因此实践建议是只有当你需要 Telegraf 的 statsd 数据与 Datadog Agent 的 rate 曲线叠加展示时才把rate_interval设为与 Datadog Agent 相同的 interval通常10s否则保持默认0s让 counter 以count类型原值上报。错误处理与可观测性小结汇总该插件的失败模式便于排障现象触发点源码位置apikey is a required field for datadog output未配置 apikeyConnect 阶段Connecterror parsing proxy url ...http_proxy_url非法proxy.goUnable to build Metric for name ... skipping字段类型无法转 float如字符串混入单条跳过并记 Info 日志convertToDatadogMetricunable to marshal TimeSeries: ...JSON 序列化失败Writereceived bad status code, code: body响应码不在 200–209返回 Datadog 响应体原文Writeerror POSTing metrics, ...密钥已打码网络/超时等请求失败Write快速上手清单在telegraf.conf中添加[[outputs.datadog]]并填入apikey可参考 sample.conf内网环境按需配置use_system_proxy/http_proxy_url需要压缩传输时设compression zlib请求头为Content-Encoding: deflate用url指向本地 mock或临时抓包代理验证负载格式与命名规则是否符合预期再改回默认端点若与 Datadog Agent 并存上报 statsd 指标设rate_interval 10s须与 Agent 的 rate interval 一致。相关代码与测试入口插件实现、单元测试、公共代理组件、内容压缩组件、statsd 输入的 metric_type tag 来源、插件通用配置文档。【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考