VictoriaMetrics报'metric对象缺失',求正确JSON上报请求体
上报VictoriaMetrics监控数据时"missing 'metric' object"错误的解决方法
问题现象
调用VictoriaMetrics的http://127.0.0.1:8428/api/v1/import接口上报监控数据,发送数组形式的JSON请求体后,收到"missing 'metric' object"错误。
错误细节
错误请求体
[ { "metric": { "__name__": "test_counter", "instance": "test-01" }, "value": [1690000000, 123] } ]
报错日志
level=error ts=2023-07-23T10:00:00.000Z caller=request_handler.go:123 msg="error processing request" url=/api/v1/import error="missing 'metric' object"
初始Go代码
package main import ( "bytes" "encoding/json" "net/http" ) type Metric struct { Metric map[string]string `json:"metric"` Value []interface{} `json:"value"` } func main() { metrics := []Metric{ { Metric: map[string]string{ "__name__": "test_counter", "instance": "test-01", }, Value: []interface{}{1690000000, 123}, }, } data, _ := json.Marshal(metrics) _, err := http.Post("http://127.0.0.1:8428/api/v1/import", "application/json", bytes.NewBuffer(data)) if err != nil { panic(err) } }
问题原因
VictoriaMetrics的/api/v1/import接口接收的是单个JSON对象,而非JSON数组。用数组包裹请求体后,接口无法解析出顶层的metric字段,因此抛出错误。
修正方案
正确的单指标请求体(非数组形式)
{ "metric": { "__name__": "test_counter", "instance": "test-01" }, "value": [1690000000, 123] }
修正后的单指标上报Go代码
package main import ( "bytes" "encoding/json" "net/http" ) type Metric struct { Metric map[string]string `json:"metric"` Value []interface{} `json:"value"` } func main() { metric := Metric{ Metric: map[string]string{ "__name__": "test_counter", "instance": "test-01", }, Value: []interface{}{1690000000, 123}, } data, _ := json.Marshal(metric) _, err := http.Post("http://127.0.0.1:8428/api/v1/import", "application/json", bytes.NewBuffer(data)) if err != nil { panic(err) } }
批量上报多指标方案
如果需要批量上报多个指标,可使用接口支持的换行分隔JSON格式(每个指标占一行),示例请求体:
{"metric": {"__name__": "test_counter", "instance": "test-01"}, "value": [1690000000, 123]} {"metric": {"__name__": "test_gauge", "instance": "test-01"}, "value": [1690000000, 45.6]}
对应的批量上报Go代码:
package main import ( "bytes" "encoding/json" "net/http" ) type Metric struct { Metric map[string]string `json:"metric"` Value []interface{} `json:"value"` } func main() { metrics := []Metric{ { Metric: map[string]string{ "__name__": "test_counter", "instance": "test-01", }, Value: []interface{}{1690000000, 123}, }, { Metric: map[string]string{ "__name__": "test_gauge", "instance": "test-01", }, Value: []interface{}{1690000000, 45.6}, }, } var buf bytes.Buffer for _, m := range metrics { data, _ := json.Marshal(m) buf.Write(data) buf.WriteByte('\n') } _, err := http.Post("http://127.0.0.1:8428/api/v1/import", "application/json", &buf) if err != nil { panic(err) } }
内容的提问来源于stack exchange,提问作者27P
相关产品推荐
相关产品推荐

