Use Prometheus SDK to upload metric data in Function Compute scenarios
Prometheus automatically generates multi-dimensional metrics with built-in labels, but its default Pull mode requires an HTTP endpoint that Function Compute cannot expose. You can use the Prometheus SDK in Push mode to send metric data directly to a Simple Log Service Metricstore.
Prerequisites
-
Simple Log Service is activated. For more information, see Activate Simple Log Service.
-
A project and a Metricstore are created. For more information, see Manage a project and Manage a metricstore.
Integrate Prometheus into Simple Log Service
Prometheus generates multi-dimensional metrics with built-in labels and uploads them to a Metricstore. The upload mode depends on your scenario.
|
Mode |
Description |
|
Pull mode |
In Pull mode, Prometheus collects and uploads metric data to Simple Log Service through the following steps:
|
|
Push mode |
In Push mode, metric data is actively pushed to a Metricstore. You can use either of the following methods:
|
Sample code
The Prometheus SDK lets you embed the collection process logic (metric gathering, encoding, and remote-write submission) directly into your project process, eliminating the need for a separate collector.
Go
Simple Log Service SDK for Go is installed. For more information, see Install Go SDK. The sample uses the Gather() function to collect all registered metrics and then calls Encode or Decode to serialize them.
package main
import (
"bytes"
"fmt"
"time"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/expfmt"
"github.com/prometheus/prometheus/util/fmtutil"
"io/ioutil"
"math/rand"
"net/http"
)
var durationHistogram = prometheus.NewHistogram(
prometheus.HistogramOpts{
Name: "server_handling_seconds",
Buckets: prometheus.DefBuckets,
},
)
var requestCount = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "server_requests_count",
},
)
func main() {
prometheus.MustRegister(durationHistogram)
// Replace your-project-name, endpoint, your-project-name, and your-metricstore-name with your actual values.
u := fmt.Sprintf("https://%s.%s/prometheus/%s/%s/api/v1/write", "your-project-name", "endpoint", "your-project-name", "your-metricstore-name")
for i := 0; i < 300; i++ {
// Update the metric data.
for j := 0; j < 100; j++ {
val := rand.Float64() * 10
durationHistogram.Observe(val)
requestCount.Inc()
}
// Collect all registered metric data.
mfs, err := prometheus.DefaultGatherer.Gather()
if err != nil {
panic(err)
}
// Encode the metric data.
// Note: The encoding process is mandatory because the "+Inf" le label for Histogram-type metrics is added during encoding.
buf := bytes.NewBuffer(nil)
encoder := expfmt.NewEncoder(buf, expfmt.NewFormat(expfmt.TypeTextPlain))
for _, mf := range mfs {
if err := encoder.Encode(mf); err != nil {
panic(err)
}
}
// Parse the encoded metric data and convert it into a request that conforms to the Remote Write protocol buffer format.
// This sample code exits immediately on an error. In a production environment, you must implement an appropriate error handling strategy, such as retrying or skipping.
request, err := fmtutil.MetricTextToWriteRequest(buf, nil)
if err != nil {
panic(err)
}
// Serialize and compress the *prompb.WriteRequest object.
data, _ := proto.Marshal(request)
bufBody := snappy.Encode(nil, data)
rwR, err := http.NewRequest("POST", u, ioutil.NopCloser(bytes.NewReader(bufBody)))
if err != nil {
panic(err)
}
rwR.Header.Add("Content-Encoding", "snappy")
rwR.Header.Set("Content-Type", "application/x-protobuf")
// Set the basic authentication information, which is your AccessKey ID and AccessKey secret.
rwR.SetBasicAuth("yourAccessKeyID", "yourAccessKeySecret")
// Send the metric data to the Simple Log Service Metricstore.
resp, err := http.DefaultClient.Do(rwR)
if err != nil {
panic(err)
}
d, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(d))
time.Sleep(time.Second)
}
}
Verify the collected data
-
Log on to the Simple Log Service console. In the Projects section, click the project that you want to manage.
On the tab, click the metricstore you want.
-
In the upper-right corner of the Metricstore page, specify a query time range. Enter a PromQL statement to calculate the 50th percentile of the total duration and click Execute Now. For more information, see PromQL.
histogram_quantile(0.5, sum by (le) (rate(server_handling_seconds_bucket[1m])))A line chart of the P50 latency metric appears, confirming that the data was collected successfully.