Last active
February 9, 2023 19:23
-
-
Save kshcherban/918b72d9ad5519aedcdc44c02c246a02 to your computer and use it in GitHub Desktop.
Write to prometheus over remote write protocol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/prometheus/client_golang/prometheus" | |
"github.com/prometheus/client_golang/prometheus/promauto" | |
"github.com/prometheus/common/model" | |
"github.com/prometheus/prometheus/prompb" | |
"github.com/golang/snappy" | |
"net/http" | |
"log" | |
"time" | |
"io/ioutil" | |
"bytes" | |
) | |
var ( | |
exampleMetric = promauto.NewGauge(prometheus.GaugeOpts{ | |
Name: "example_metric", | |
Help: "An example metric", | |
}) | |
) | |
func main() { | |
// Set the value of the metric | |
exampleMetric.Set(42) | |
// Create a Prometheus TimeSeries for the metric | |
ts := prompb.TimeSeries{ | |
Labels: []prompb.Label{ | |
{ | |
Name: "__name__", | |
Value: "example_metric", | |
}, | |
}, | |
Samples: []prompb.Sample{ | |
{ | |
Value: 42, | |
Timestamp: int64(model.TimeFromUnix(time.Now().Unix())), | |
}, | |
}, | |
} | |
// Create a Prometheus WriteRequest | |
req := &prompb.WriteRequest{ | |
// Timeseries: []*prompb.TimeSeries{ts}, | |
Timeseries: make([]prompb.TimeSeries, 0, 0), | |
} | |
req.Timeseries = append(req.Timeseries, ts) | |
// Compress and encode the WriteRequest | |
data, err := req.Marshal() | |
if err != nil { | |
log.Fatalf("error marshaling request: %v", err) | |
} | |
compressed := snappy.Encode(nil, data) | |
// Push the WriteRequest to Prometheus | |
resp, err := http.Post("http://localhost:9090/api/v1/write", "application/x-protobuf", bytes.NewBuffer(compressed)) | |
if err != nil { | |
log.Fatalf("error sending request: %v", err) | |
} | |
defer resp.Body.Close() | |
// Check the response from Prometheus | |
b, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
log.Fatalf("error reading response: %v", err) | |
} | |
if resp.StatusCode != http.StatusOK { | |
log.Fatalf("unexpected status code: %d, body: %s", resp.StatusCode, b) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment