Simple Log Service (SLS) provides Prometheus-compatible APIs for querying time series metrics and writing data to a MetricStore, including endpoint details, request parameters, authentication methods, and error handling.
Overview
Prometheus APIs are served under the /api/v1 path. MetricStore APIs follow the same convention. The full URL format is https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/.
Parameter | Required | Description |
{sls-endpoint} | Yes | A service endpoint is the domain name used to access SLS. The endpoint is specific to the region where the Project is located. For more information, see Service Endpoints. |
{project} | Yes | Project name: A Project is the resource management unit of SLS and the primary boundary for multi-user isolation and access control. For more information, see Manage Projects. |
{metricstore} | Yes | The name of your MetricStore. For creation instructions, see Create a MetricStore. |
These APIs require Basic authentication. Set Username to your AccessKey ID and Password to your AccessKey Secret. For security, use a RAM user's AccessKey pair. Grant the RAM user the required permissions on the target Project. For more information, see Configure Permission Assistant.
STS authentication is also supported. When using STS, set the Password in BasicAuth to {AccessKey Secret}${STS token}. For more information, see What is STS.
Time series metric query APIs
The time series metric query APIs include the instant query API and the range query API.
Instant query API
The instant query API queries metric data at a specific point in time.
GET https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/query
POST https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/queryParameters:
Parameter | Required | Description |
query | Yes | The PromQL expression. For more information, see PromQL syntax. |
time | No | The evaluation timestamp as a Unix timestamp in seconds. Default: the current time. |
timeout | No | The query timeout in seconds. Also supports time duration formats such as |
lookback_delta | No | Overrides the Prometheus |
This API returns the following four result types:
vector
Sample code
curl -X GET 'http://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/query?query=up&time=1676700699' \ -u username:password \ -H 'Content-Type: application/x-www-form-urlencoded' # Set username to your AccessKey ID and password to your AccessKey Secret.Result
{ "status": "success", "data": { "resultType": "vector", "result": [ { "metric": { "__name__": "up", "instance": "demo.promlabs.com:10001", "job": "demo" }, "value": [ 1676700550.696, "1" ] }, { "metric": { "__name__": "up", "instance": "demo.promlabs.com:10000", "job": "demo" }, "value": [ 1676700550.696, "1" ] } ] } }
scalar
Sample code
curl -X GET 'http://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/query?query=2-1&time=1676700699' \ -u username:password \ -H 'Content-Type: application/x-www-form-urlencoded' # Set username to your AccessKey ID and password to your AccessKey Secret.Result
{ "status": "success", "data": { "resultType": "scalar", "result": [ 1676700699, "0" ] } }
string
Sample code
curl -X GET 'http://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/query?query="test_string"&time=1676700699' \ -u username:password \ -H 'Content-Type: application/x-www-form-urlencoded' # Set username to your AccessKey ID and password to your AccessKey Secret.Result
{ "status": "success", "data": { "resultType": "string", "result": [ 1676700699, "test_string" ] } }
matrix
Sample code
curl -X GET 'http://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/query?query=up[1m]&time=1743414624' \ -u username:password \ -H 'Content-Type: application/x-www-form-urlencoded' # Set username to your AccessKey ID and password to your AccessKey Secret.Result
{ "status": "success", "data": { "resultType": "matrix", "result": [ { "metric": { "__name__": "up", "instance": "demo.promlabs.com:10000", "job": "demo" }, "values": [ [ 1743414609.803, "1" ], [ 1743414614.803, "1" ], [ 1743414619.803, "1" ] ] }, { "metric": { "__name__": "up", "instance": "demo.promlabs.com:10001", "job": "demo" }, "values": [ [ 1743414611.078, "1" ], [ 1743414616.078, "1" ], [ 1743414621.078, "1" ] ] } ] } }
Range query API
The range query API queries metric data at multiple time points within a specified time range.
GET https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/query_range
POST https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/query_rangeParameters:
Parameter | Required | Description |
query | Yes | The PromQL expression. For more information, see PromQL syntax. |
start | No | The start of the query range as a Unix timestamp in seconds. |
end | No | The end of the query range as a Unix timestamp in seconds. |
step | No | The query resolution step in seconds. Also supports time duration formats such as |
timeout | No | The query timeout in seconds. Also supports time duration formats such as |
lookback_delta | No | Overrides the Prometheus |
Sample code
Query metric data from 14:09:59 on February 18, 2023 to 14:16:39 on February 18, 2023, with a
stepof 60s.curl -X GET 'https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/query_range?query=up&start=1676700599&end=1676700999&step=60s' \ -u username:password \ -H 'Content-Type: application/x-www-form-urlencoded' # Set username to your AccessKey ID and password to your AccessKey Secret.Result
{ "status": "success", "data": { "resultType": "matrix", "result": [ { "metric": { "__name__": "up", "instance": "demo.promlabs.com:10000", "job": "demo" }, "values": [ [ 1676700599, "1" ], [ 1676700659, "1" ], [ 1676700719, "0" ], [ 1676700779, "0" ], [ 1676700839, "1" ], [ 1676700899, "0" ], [ 1676700959, "1" ] ] }, { "metric": { "__name__": "up", "instance": "demo.promlabs.com:10001", "job": "demo" }, "values": [ [ 1676700599, "1" ], [ 1676700659, "1" ], [ 1676700719, "0" ], [ 1676700779, "0" ], [ 1676700839, "1" ], [ 1676700899, "1" ], [ 1676700959, "1" ] ] } ] } }
Metadata query APIs
SLS also supports metadata query APIs compatible with the Prometheus Querying metadata endpoints. These APIs retrieve metric names, labels, and label values within a time range, excluding timestamps and sample values.
Query series API
The query series API retrieves all metric names and their label key-value pairs that match specific selectors within a time range.
GET https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/series
POST https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/seriesParameters:
Parameter | Required | Description |
match[] | Yes | The series selectors to match. For example, Supports one or more |
start | No | The start of the query range, as a Unix timestamp in seconds. Default: 5 minutes before the current time. |
end | No | The end of the query range, as a Unix timestamp in seconds. Default: the current time. Important If you specify custom values for both the start and end parameters, the API limits the query to the 5-minute interval before the end time. The effective query range is [ |
x-sls-disable-range-limit | No | Set to |
forceMaxMetaTimeRangeSeconds | No | The maximum query time range in seconds. If the duration between Set this parameter to improve query efficiency. |
Sample request
curl -g -X GET 'https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/series?match[]=up{instance="demo.promlabs.com:10000"}&match[]=go_sched_latencies_seconds_bucket&start=1676700599&end=1676700999' \ -u username:password \ -H 'Content-Type: application/x-www-form-urlencoded' # Set username to your AccessKey ID and password to your AccessKey Secret.Result
{ "status": "success", "data": [ { "__name__": "go_gc_duration_seconds_count", "instance": "demo.promlabs.com:10000", "job": "demo" }, { "__name__": "go_gc_duration_seconds_count", "instance": "demo.promlabs.com:10001", "job": "demo" }, { "__name__": "up", "instance": "demo.promlabs.com:10000", "job": "demo" } ] }
Query label names API
The query label names API retrieves all label names from series that match the specified selectors within a time range.
GET https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/labels
POST https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/labelsParameters:
Parameter | Required | Description |
match[] | Yes | The series selectors to match. For example, Supports zero, one, or more |
start | No | The start of the query range, as a Unix timestamp in seconds. Default: 5 minutes before the current time. |
end | No | The end of the query range, as a Unix timestamp in seconds. Default: the current time. Important If you specify custom values for both the start and end parameters, the API limits the query to the 5-minute interval before the end time. The effective query range is [ |
x-sls-disable-range-limit | No | Set to |
forceMaxMetaTimeRangeSeconds | No | The maximum query time range in seconds. If the duration between Set this parameter to improve query efficiency. |
Sample request
Retrieve all label names for all metrics within the specified time range.
curl -X GET 'https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/labels?start=1676700599&end=1676700999' \ -u username:password \ -H 'Content-Type: application/x-www-form-urlencoded' # Set username to your AccessKey ID and password to your AccessKey Secret.Result
{ "status": "success", "data": [ "code", "instance", "job", "le", "method", "mode", "path", "quantile", "status", "type", "version", "__name__" ] }
Query label values API
The query label values API retrieves all values for a specific label name from series that match the specified selectors within a time range.
Replace <label_name> in the API URL with a specific label name.
GET https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/label/<label_name>/valuesParameters:
Parameter | Required | Description |
match[] | Yes | The series selectors to match. For example, Supports one or more |
start | No | The start of the query range, as a Unix timestamp in seconds. Default: 5 minutes before the current time. |
end | No | The end of the query range, as a Unix timestamp in seconds. Default: the current time. Important If you specify custom values for both the start and end parameters, the API limits the query to the 5-minute interval before the end time. The effective query range is [ |
x-sls-disable-range-limit | No | Set to |
forceMaxMetaTimeRangeSeconds | No | The maximum query time range in seconds. If the duration between Set this parameter to improve query efficiency. |
Sample request
Retrieve all values for the instance label from the up metric within the specified time range.
curl -X GET 'https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/label/instance/values?match[]=up&start=1676700599&end=1676700999' \ -u username:password \ -H 'Content-Type: application/x-www-form-urlencoded' # Set username to your AccessKey ID and password to your AccessKey Secret.Result
{ "status": "success", "data": [ "demo.promlabs.com:10000", "demo.promlabs.com:10001", "demo.promlabs.com:10002" ] }
Data write API
Ingest time series data to a MetricStore by configuring the remote_write parameter in your Prometheus configuration file. For more information, see Use the remote write protocol to ingest Prometheus monitoring data. MetricStore is compatible with the Prometheus remote write protocol. Direct HTTP requests to the remote write endpoint are also supported, without requiring a running Prometheus process.
MetricStore provides the following remote write endpoint for parsing and storing time series data.
When writing time series data to the SLS time series database through the remote write protocol, SLS uses the metric name and labels as the hash key by default. This routes data from different time series to specific shards, improving data locality in the backend storage.
POST https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}/api/v1/writeSample Go implementation for the remote write API:
import (
"bytes"
"flag"
"fmt"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/prometheus/prometheus/prompb"
"io/ioutil"
"net/http"
"time"
)
func MockRemoteWrite() {
project := flag.String("project", "xxxx", "")
metricStore := flag.String("metricstore", "xxxx", "")
endpoint := flag.String("endpoint", "xxxx", "")
akId := flag.String("akid", "xxxx", "") // Your AccessKey ID.
akKey := flag.String("aksecret", "xxxx", "") // Your AccessKey Secret.
flag.Parse()
Url := fmt.Sprintf("https://%s.%s/prometheus/%s/%s/api/v1/write", *project, *endpoint, *project, *metricStore)
timestamp := time.Now().UnixNano()
timeSeries := []prompb.TimeSeries{
{
Labels: []prompb.Label{
{Name: "__name__", Value: "test_metric"},
{Name: "app", Value: "HOST"},
{Name: "device", Value: "vda"},
},
Samples: []prompb.Sample{
{Timestamp: timestamp / 1000000, Value: 100},
{Timestamp: timestamp/1000000 + 10000, Value: 200},
{Timestamp: timestamp/1000000 + 20000, Value: 400},
{Timestamp: timestamp/1000000 + 30000, Value: 300},
},
},
{
Labels: []prompb.Label{
{Name: "__name__", Value: "test_metric"},
{Name: "app", Value: "HOST"},
{Name: "device", Value: "vda"},
{Name: "uid", Value: "123456"},
},
Samples: []prompb.Sample{
{Timestamp: timestamp / 1000000, Value: 100},
{Timestamp: timestamp/1000000 + 10000, Value: 200},
{Timestamp: timestamp/1000000 + 20000, Value: 400},
{Timestamp: timestamp/1000000 + 30000, Value: 600},
},
},
}
data, _ := proto.Marshal(&prompb.WriteRequest{Timeseries: timeSeries})
bufBody := snappy.Encode(nil, data)
rwR, err := http.NewRequest("POST", Url, ioutil.NopCloser(bytes.NewReader(bufBody)))
rwR.Header.Add("Content-Encoding", "snappy")
rwR.Header.Set("Content-Type", "application/x-protobuf")
rwR.SetBasicAuth(*akId, *akKey) // Set Basic Authentication.
if err != nil {
fmt.Println(err.Error())
return
}
start := time.Now().UnixNano() / 1000000 // ms
do, err := client.Do(rwR)
end := time.Now().UnixNano() / 1000000 // ms
if err != nil {
panic(err)
}
status, result := parseResp(do)
fmt.Println("status:", status, "result:", result, "duration:", end-start)
}
func parseResp(resp *http.Response) (status, data string) {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) // The response body must be fully read.
if err != nil {
panic(err)
}
return resp.Status, string(body)
}SDK examples
HTTP
import (
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const separator = "#"
func http_main() {
project := flag.String("project", "xxxx", "")
metricStore := flag.String("metricstore", "xxxx", "")
endpoint := flag.String("endpoint", "xxxx", "")
akId := flag.String("akid", "xxxx", "")
akKey := flag.String("aksecret", "xxxx", "")
query := flag.String("query", "avg(up)", "")
queryType := flag.String("type", "values", "range or query or labels or values or series")
matches := flag.String("match", "up", "") // Use a number sign (#) to separate multiple match[] parameters.
labelName := flag.String("label", "instance", "")
step := flag.String("step", "1m", "")
fromtime := flag.String("from", "2023-02-15T00:00:00Z", "time 2006-01-02T15:04:05Z07:00")
totime := flag.String("to", "2023-02-15T00:15:00Z", "time 2006-01-02T15:04:05Z07:00")
flag.Parse()
timeFrom, err := time.Parse(time.RFC3339, *fromtime)
if err != nil {
panic(err)
}
timeTo, err := time.Parse(time.RFC3339, *totime)
if err != nil {
panic(err)
}
// URL: https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}
prometheusEndpoint := fmt.Sprintf("https://%s/prometheus/%s/%s", *project+"."+*endpoint, *project, *metricStore)
var uri string
urlVal := url.Values{}
urlVal.Add("start", strconv.FormatInt(timeFrom.Unix(), 10))
urlVal.Add("end", strconv.FormatInt(timeTo.Unix(), 10))
switch *queryType {
case "range":
urlVal.Add("query", *query)
urlVal.Add("step", *step)
uri = fmt.Sprintf("%s/api/v1/query_range?%v", prometheusEndpoint, urlVal.Encode())
case "query":
urlVal.Add("query", *query)
urlVal.Add("time", strconv.FormatInt(timeTo.Unix(), 10))
uri = fmt.Sprintf("%s/api/v1/query?%v", prometheusEndpoint, urlVal.Encode())
case "labels":
extractAddMatches(*matches, urlVal)
uri = fmt.Sprintf("%s/api/v1/labels?%v", prometheusEndpoint, urlVal.Encode())
case "values":
extractAddMatches(*matches, urlVal)
uri = fmt.Sprintf("%s/api/v1/label/%s/values?%v", prometheusEndpoint, *labelName, urlVal.Encode())
case "series":
extractAddMatches(*matches, urlVal)
uri = fmt.Sprintf("%s/api/v1/series?%v", prometheusEndpoint, urlVal.Encode())
}
req, _ := http.NewRequest(http.MethodGet, uri, nil)
req.SetBasicAuth(*akId, *akKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
buf, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
panic(err)
}
fmt.Println(string(buf))
}
func extractAddMatches(matches string, uVal url.Values) {
splits := strings.Split(matches, separator)
for _, match := range splits {
uVal.Add("match[]", match)
}
}Prometheus SDK
The following example uses Prometheus client_golang v1.14.0.
import (
"context"
"flag"
"fmt"
"github.com/prometheus/client_golang/api"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"net"
"net/http"
"net/url"
"time"
)
func main() {
project := flag.String("project", "xxxx", "")
metricStore := flag.String("metricstore", "xxxx", "")
endpoint := flag.String("endpoint", "xxxx", "")
akId := flag.String("akid", "xxxx", "")
akKey := flag.String("aksecret", "xxxx", "")
flag.Parse()
// URL: https://{project}.{sls-endpoint}/prometheus/{project}/{metricstore}
prometheusEndpoint := fmt.Sprintf("https://%s.%s/prometheus/%s/%s", *project, *endpoint, *project, *metricStore)
client, err := api.NewClient(api.Config{
Address: prometheusEndpoint,
RoundTripper: &http.Transport{
// Set Basic Auth
Proxy: func(req *http.Request) (*url.URL, error) {
req.SetBasicAuth(*akId, *akKey)
return nil, nil
},
DialContext: (&net.Dialer{
Timeout: 60 * time.Second,
KeepAlive: 60 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
},
})
if err != nil {
panic(err)
}
v1api := v1.NewAPI(client)
ctx, _ := context.WithTimeout(context.Background(), 60*time.Second)
r := v1.Range{
Start: time.Now().Add(-15 * time.Minute),
End: time.Now(),
Step: time.Minute,
}
// query range
result, warnings, err := v1api.QueryRange(ctx, "avg(up)", r)
if err != nil {
panic(err)
}
if len(warnings) > 0 {
fmt.Printf("Warnings: %v %v\n", warnings, result)
}
fmt.Println(result)
// query
result, warnings, err = v1api.Query(ctx, "avg(up)", time.Now())
if err != nil {
panic(err)
}
if len(warnings) > 0 {
fmt.Printf("Warnings: %v %v\n", warnings, result)
}
fmt.Println(result)
// series
series, warnings, err := v1api.Series(ctx, []string{"up"}, time.Now().Add(-15*time.Minute), time.Now())
if err != nil {
panic(err)
}
if len(warnings) > 0 {
fmt.Printf("Warnings: %v %v\n", warnings, result)
}
fmt.Println(series)
// labels
names, warnings, err := v1api.LabelNames(ctx, []string{"up"}, time.Now().Add(-15*time.Minute), time.Now())
if err != nil {
panic(err)
}
if len(warnings) > 0 {
fmt.Printf("Warnings: %v %v\n", warnings, result)
}
fmt.Println(names)
// labelValues
values, warnings, err := v1api.LabelValues(ctx, "instance", []string{"up"}, time.Now().Add(-15*time.Minute), time.Now())
if err != nil {
panic(err)
}
if len(warnings) > 0 {
fmt.Printf("Warnings: %v %v\n", warnings, result)
}
fmt.Println(values)
}Response structure
The query and write APIs return responses in the following structure:
{
"status": "success" | "error",
"data": <data>,
// Returned when a query evaluation error occurs.
"errorType": "<string>",
"error": "<string>",
// Returned to indicate a potentially incomplete query.
"warnings": ["<string>"]
}Error handling
The following sections describe common errors and their resolutions.
Authentication failure
The following response indicates an authentication failure. Verify that your AccessKey credentials are correct.
{ "status": "error", "code": "401", "errorType": "unauthorized", "error": "get query instance error: {\n \"httpCode\": 401,\n \"errorCode\": \"Unauthorized\",\n \"errorMessage\": \"AccessKeyId not found: xxxx\",\n \"requestID\": \"xxxx\"\n}" }This error can also occur if the source IP address is not in the VPC CIDR block whitelist. Add the IP address to the VPC CIDR block whitelist.
{ "status": "error", "code": "401", "errorType": "unauthorized", "error": "get query instance error: {\n \"httpCode\": 401,\n \"errorCode\": \"Unauthorized\",\n \"errorMessage\": \"AccessKeyId not found: xxxx\",\n \"requestID\": \"xxxx\"\n}" }
PromQL syntax error
The following response indicates an invalid PromQL expression. Correct the expression in the query parameter.
--> /api/v1/query_range?query=up[2m]&start=1676700599&end=1676700999&step=60s
{
"status": "error",
"errorType": "bad_data",
"error": "invalid expression type \"range vector\" for range query, must be Scalar or instant Vector"
}Timeout error
The following response indicates a query timeout. Increase the timeout value.
{
"status": "error",
"errorType": "timeout",
"error": "query timed out in expression evaluation"
}Incomplete query
A response with warnings indicates an incomplete result. Narrow the time range and retry the query.
{
"status": "success",
"data": {
"resultType": "matrix",
"result": [
{
"metric": {},
"values": [
[
1673798460,
"11111111"
],
[
1673799060,
"22222222"
],
[
1673799660,
"33333333"
]
]
}
]
},
"warnings": [
"Request to Sls partial incompleted, incomplete task count : 11, total : 108"
]
}