1. 创建链接

1.1 语法

func NewClient(cfg Config) (Client, error)
type Config struct {
    Address      string
    Client       *http.Client
    RoundTripper http.RoundTripper
}
	client, err = api.NewClient(api.Config{
		Address: "http://10.10.182.112:9090",
	})

1.2 完整示例

package main

import (
	"fmt"
	"github.com/prometheus/client_golang/api"
)

func CreatClient() (client api.Client, err error) {
	client, err = api.NewClient(api.Config{
		Address: "http://10.10.182.112:9090",
	})
	if err != nil {
		fmt.Printf("Error creating client: %vn", err)
		return nil, err
	}
	return client, nil
}


func main() {
	client, err := CreatClient()
	if err != nil {
		fmt.Errorf("%+v", err)
	}
	if client != nil {
		fmt.Println("client创建成功")
	}
}

2. 简单查询

2.1 语法

func NewAPI(c Client) API
func (API) Query(ctx context.Context, query string, ts time.Time, opts ...Option) (Value, Warnings, error)
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
	v1api := proV1.NewAPI(Client)
	ctx := context.Background()
	result, warnings, err := v1api.Query(ctx, "up", time.Now(), proV1.WithTimeout(5*time.Second))

2.2 完整示例

package main

import (
	"context"
	"fmt"
	"github.com/prometheus/client_golang/api"
	proV1 "github.com/prometheus/client_golang/api/prometheus/v1"
	"github.com/prometheus/common/model"
	"time"
)

var Client api.Client

func init() {
	Client, _ = CreatClient()
}

func CreatClient() (client api.Client, err error) {
	client, err = api.NewClient(api.Config{
		Address: "http://10.10.181.112:9090",
	})
	if err != nil {
		fmt.Printf("Error creating client: %vn", err)
		return nil, err
	}
	return client, nil
}

func Query() (result model.Value, err error) {
	v1api := proV1.NewAPI(Client)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	result, warnings, err := v1api.Query(ctx, "up", time.Now(), proV1.WithTimeout(5*time.Second))
	if err != nil {
		return nil, err
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %vn", warnings)
	}
	return result, nil
}

func main() {
	result, err := Query()
	if err != nil {
		fmt.Errorf("%q", err)
	}
	fmt.Printf("Result:n%vn", result)
}

3. 范围查询

3.1 语法

type Range struct {
    Start, End time.Time
    Step       time.Duration
}

语法示例

	r := proV1.Range{
		Start: time.Now().Add(-time.Hour),
		End:   time.Now(),
		Step:  time.Minute,
	}
func (API) QueryRange(ctx context.Context, query string, r Range, opts ...Option) (Value, Warnings, error)

语法示例

result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r, proV1.WithTimeout(5*time.Second))

3.2 完整示例

package main

import (
	"context"
	"fmt"
	"github.com/prometheus/client_golang/api"
	proV1 "github.com/prometheus/client_golang/api/prometheus/v1"
	"github.com/prometheus/common/model"
	"time"
)

var Client api.Client

func init() {
	Client, _ = CreatClient()
}

func CreatClient() (client api.Client, err error) {
	client, err = api.NewClient(api.Config{
		Address: "http://10.10.181.112:9090",
	})
	if err != nil {
		fmt.Printf("Error creating client: %vn", err)
		return nil, err
	}
	return client, nil
}

func QueryRange() (result model.Value, err error) {
	v1api := proV1.NewAPI(Client)
	//ctx := context.Background()
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	r := proV1.Range{
		Start: time.Now().Add(-time.Hour),
		End:   time.Now(),
		Step:  time.Minute,
	}
	defer cancel()
	result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r, proV1.WithTimeout(5*time.Second))
	if err != nil {
		return nil, err
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %vn", warnings)
	}
	return result, nil
}

func main() {
	result, err := QueryRange()
	if err != nil {
		fmt.Errorf("%q", err)
	}
	fmt.Printf("Result:n%vn", result)
}

4. 获取指标名称标签

4.1 语法

  • 语法
func (API) Series(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) ([]model.LabelSet, Warnings, error)
  • 语法示例
	lbls, warnings, err := v1api.Series(ctx, []string{
		"{__name__=~".+",job="prometheus"}",
	}, time.Now().Add(-time.Hour), time.Now())

说明

比如示例中的job="prometheus",是我们prometheus配置文件里写的job名。

  • LabelSet
type LabelSet map[LabelName]LabelValue

可以看到LabelSet实际是一个map,因此我们可以打印示例中的指标名:

	for _, lbl := range lbls {
		fmt.Println(lbl["__name__"])
	}

4.1 完整示例(获取所有数据条目)

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/prometheus/client_golang/api"
	proV1 "github.com/prometheus/client_golang/api/prometheus/v1"
)

var Client api.Client

func init() {
	Client, _ = CreatClient()
}

func CreatClient() (client api.Client, err error) {
	client, err = api.NewClient(api.Config{
		Address: "http://10.10.181.112:9090",
	})
	if err != nil {
		fmt.Printf("Error creating client: %vn", err)
		return nil, err
	}
	return client, nil
}

func ExampleAPI_series() {
	v1api := proV1.NewAPI(Client)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	lbls, warnings, err := v1api.Series(ctx, []string{
		//"{__name__=~"scrape_.+",job="node"}",
		"{__name__=~".+"}",
	}, time.Now().Add(-time.Hour), time.Now())
	if err != nil {
		fmt.Printf("Error querying Prometheus: %vn", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %vn", warnings)
	}
	fmt.Println("Result:", len(lbls))
	for _, lbl := range lbls {
		//fmt.Println(lbl["__name__"])
		fmt.Println(lbl)
	}
}
func main() {
	ExampleAPI_series()
}

【附官方示例】

https://github.com/prometheus/client_golang/blob/main/api/prometheus/v1/example_test.go

package v1_test

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"time"

	"github.com/prometheus/common/config"

	"github.com/prometheus/client_golang/api"
	v1 "github.com/prometheus/client_golang/api/prometheus/v1"
)

func ExampleAPI_query() {
	client, err := api.NewClient(api.Config{
		Address: "http://demo.robustperception.io:9090",
	})
	if err != nil {
		fmt.Printf("Error creating client: %vn", err)
		os.Exit(1)
	}

	v1api := v1.NewAPI(client)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	result, warnings, err := v1api.Query(ctx, "up", time.Now(), v1.WithTimeout(5*time.Second))
	if err != nil {
		fmt.Printf("Error querying Prometheus: %vn", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %vn", warnings)
	}
	fmt.Printf("Result:n%vn", result)
}

func ExampleAPI_queryRange() {
	client, err := api.NewClient(api.Config{
		Address: "http://demo.robustperception.io:9090",
	})
	if err != nil {
		fmt.Printf("Error creating client: %vn", err)
		os.Exit(1)
	}

	v1api := v1.NewAPI(client)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	r := v1.Range{
		Start: time.Now().Add(-time.Hour),
		End:   time.Now(),
		Step:  time.Minute,
	}
	result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r, v1.WithTimeout(5*time.Second))
	if err != nil {
		fmt.Printf("Error querying Prometheus: %vn", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %vn", warnings)
	}
	fmt.Printf("Result:n%vn", result)
}

type userAgentRoundTripper struct {
	name string
	rt   http.RoundTripper
}

// RoundTrip implements the http.RoundTripper interface.
func (u userAgentRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
	if r.UserAgent() == "" {
		// The specification of http.RoundTripper says that it shouldn't mutate
		// the request so make a copy of req.Header since this is all that is
		// modified.
		r2 := new(http.Request)
		*r2 = *r
		r2.Header = make(http.Header)
		for k, s := range r.Header {
			r2.Header[k] = s
		}
		r2.Header.Set("User-Agent", u.name)
		r = r2
	}
	return u.rt.RoundTrip(r)
}

func ExampleAPI_queryRangeWithUserAgent() {
	client, err := api.NewClient(api.Config{
		Address:      "http://demo.robustperception.io:9090",
		RoundTripper: userAgentRoundTripper{name: "Client-Golang", rt: api.DefaultRoundTripper},
	})
	if err != nil {
		fmt.Printf("Error creating client: %vn", err)
		os.Exit(1)
	}

	v1api := v1.NewAPI(client)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	r := v1.Range{
		Start: time.Now().Add(-time.Hour),
		End:   time.Now(),
		Step:  time.Minute,
	}
	result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)
	if err != nil {
		fmt.Printf("Error querying Prometheus: %vn", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %vn", warnings)
	}
	fmt.Printf("Result:n%vn", result)
}

func ExampleAPI_queryRangeWithBasicAuth() {
	client, err := api.NewClient(api.Config{
		Address: "http://demo.robustperception.io:9090",
		// We can use amazing github.com/prometheus/common/config helper!
		RoundTripper: config.NewBasicAuthRoundTripper("me", "defintely_me", "", api.DefaultRoundTripper),
	})
	if err != nil {
		fmt.Printf("Error creating client: %vn", err)
		os.Exit(1)
	}

	v1api := v1.NewAPI(client)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	r := v1.Range{
		Start: time.Now().Add(-time.Hour),
		End:   time.Now(),
		Step:  time.Minute,
	}
	result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)
	if err != nil {
		fmt.Printf("Error querying Prometheus: %vn", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %vn", warnings)
	}
	fmt.Printf("Result:n%vn", result)
}

func ExampleAPI_queryRangeWithAuthBearerToken() {
	client, err := api.NewClient(api.Config{
		Address: "http://demo.robustperception.io:9090",
		// We can use amazing github.com/prometheus/common/config helper!
		RoundTripper: config.NewAuthorizationCredentialsRoundTripper("Bearer", "secret_token", api.DefaultRoundTripper),
	})
	if err != nil {
		fmt.Printf("Error creating client: %vn", err)
		os.Exit(1)
	}

	v1api := v1.NewAPI(client)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	r := v1.Range{
		Start: time.Now().Add(-time.Hour),
		End:   time.Now(),
		Step:  time.Minute,
	}
	result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)
	if err != nil {
		fmt.Printf("Error querying Prometheus: %vn", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %vn", warnings)
	}
	fmt.Printf("Result:n%vn", result)
}

func ExampleAPI_series() {
	client, err := api.NewClient(api.Config{
		Address: "http://demo.robustperception.io:9090",
	})
	if err != nil {
		fmt.Printf("Error creating client: %vn", err)
		os.Exit(1)
	}

	v1api := v1.NewAPI(client)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	lbls, warnings, err := v1api.Series(ctx, []string{
		"{__name__=~"scrape_.+",job="node"}",
		"{__name__=~"scrape_.+",job="prometheus"}",
	}, time.Now().Add(-time.Hour), time.Now())
	if err != nil {
		fmt.Printf("Error querying Prometheus: %vn", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %vn", warnings)
	}
	fmt.Println("Result:")
	for _, lbl := range lbls {
		fmt.Println(lbl)
	}
}

在这里插入图片描述

原文地址:https://blog.csdn.net/xingzuo_1840/article/details/132357330

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_48492.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注