Windows Server推送指标至Prometheus Pushgateway遇错求助
解决Pushgateway指标推送格式错误及携带实例IP问题
一、修复指标推送格式错误
你遇到的text format parsing error是因为指标格式不符合Prometheus文本规范,加上PowerShell处理换行和请求体的方式有误,按以下步骤修正:
修正指标字符串格式
Prometheus文本格式要求每行格式为:metric_name{标签键="标签值"} 数值 [时间戳],你原写法custom_metric $number 1错误地多写了一个1,应将统计到的请求数$number作为指标值。处理文件读取的多余空白
Get-Content -Raw会读取文件所有内容(包括末尾换行),需用Trim()去除多余空白字符,避免引入无效格式字符。正确构造请求并设置Content-Type
发送请求时必须指定Content-Type: text/plain,确保Pushgateway能正确解析格式,同时保证指标字符串末尾带有换行符。
正确的PowerShell脚本示例
# 读取统计的请求数并去除多余空白 $number = (Get-Content -Path "C:\path\to\your\numberfile.txt" -Raw).Trim() # 构造符合Prometheus规范的指标字符串,末尾加换行符 $metricString = "custom_api_requests_total $number`n" # 推送至Pushgateway,指定Content-Type Invoke-WebRequest -Uri "http://localhost:9091/metrics/job/your_job" -Method Post -Body $metricString -ContentType "text/plain"
如果需要给指标添加自定义标签(比如接口类型),可修改指标字符串为:
$metricString = "custom_api_requests_total{api_type='rest'} $number`n"
二、推送指标时携带实例IP
有两种便捷方式添加实例IP标识:
方式1:在Pushgateway的URL路径中指定instance标签
Pushgateway支持通过URL路径直接设置job和instance标签,格式为:
http://localhost:9091/metrics/job/你的任务名/instance/实例IP
示例脚本:
# 获取当前服务器的IPv4地址(排除回环地址) $instanceIp = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.InterfaceAlias -notlike "*Loopback*"}).IPAddress[0] $pushUrl = "http://localhost:9091/metrics/job/your_job/instance/$instanceIp" Invoke-WebRequest -Uri $pushUrl -Method Post -Body $metricString -ContentType "text/plain"
方式2:在指标字符串中添加instance标签
直接在指标的标签部分加入instance信息,示例:
$instanceIp = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.InterfaceAlias -notlike "*Loopback*"}).IPAddress[0] $metricString = "custom_api_requests_total{instance='$instanceIp', job='your_job'} $number`n" Invoke-WebRequest -Uri "http://localhost:9091/metrics/job/your_job" -Method Post -Body $metricString -ContentType "text/plain"
说明
- 方式1更简洁,Pushgateway会自动将URL中的
instance作为指标标签; - 方式2适合需要自定义更多标签的场景,灵活性更高。
内容的提问来源于stack exchange,提问作者Jagadish Kumar
相关产品推荐
相关产品推荐

