欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

golang獲取prometheus數(shù)據(jù)(prometheus/client_golang包)

 更新時(shí)間:2025年03月02日 09:26:35   作者:玄德公筆記  
本文主要介紹了使用Go語言的prometheus/client_golang包來獲取Prometheus監(jiān)控?cái)?shù)據(jù),具有一定的參考價(jià)值,感興趣的可以了解一下

1. 創(chuàng)建鏈接

1.1 語法

  • 語法
func NewClient(cfg Config) (Client, error)
  • 結(jié)構(gòu)體
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: %v\n", 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創(chuàng)建成功")
	}
}

2. 簡單查詢

2.1 語法

  • 創(chuàng)建API實(shí)例
func NewAPI(c Client) API
  • 查詢
func (API) Query(ctx context.Context, query string, ts time.Time, opts ...Option) (Value, Warnings, error)
  • 在context中設(shè)置超時(shí)
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: %v\n", 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: %v\n", warnings)
	}
	return result, nil
}

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

3. 范圍值查詢

3.1 語法

  • 范圍設(shè)置
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: %v\n", 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: %v\n", warnings)
	}
	return result, nil
}

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

4. 獲取指標(biāo)名稱和標(biāo)簽

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())

說明:

  • 數(shù)組里可以寫多條
  • __name__ 表示指標(biāo)名,等號(hào)后邊支持正則匹配。
  • 后邊可以接一些label,同樣支持正則。

比如示例中的job=\"prometheus\",是我們?cè)趐rometheus配置文件里寫的job名。

  • LabelSet
type LabelSet map[LabelName]LabelValue

可以看到LabelSet實(shí)際是一個(gè)map,因此我們可以只打印示例中的指標(biāo)名:

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

4.1 完整示例(獲取所有數(shù)據(jù)條目)

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: %v\n", 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: %v\n", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %v\n", 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: %v\n", 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: %v\n", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %v\n", warnings)
	}
	fmt.Printf("Result:\n%v\n", result)
}

func ExampleAPI_queryRange() {
	client, err := api.NewClient(api.Config{
		Address: "http://demo.robustperception.io:9090",
	})
	if err != nil {
		fmt.Printf("Error creating client: %v\n", 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: %v\n", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %v\n", warnings)
	}
	fmt.Printf("Result:\n%v\n", 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: %v\n", 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: %v\n", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %v\n", warnings)
	}
	fmt.Printf("Result:\n%v\n", 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: %v\n", 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: %v\n", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %v\n", warnings)
	}
	fmt.Printf("Result:\n%v\n", 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: %v\n", 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: %v\n", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %v\n", warnings)
	}
	fmt.Printf("Result:\n%v\n", result)
}

func ExampleAPI_series() {
	client, err := api.NewClient(api.Config{
		Address: "http://demo.robustperception.io:9090",
	})
	if err != nil {
		fmt.Printf("Error creating client: %v\n", 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: %v\n", err)
		os.Exit(1)
	}
	if len(warnings) > 0 {
		fmt.Printf("Warnings: %v\n", warnings)
	}
	fmt.Println("Result:")
	for _, lbl := range lbls {
		fmt.Println(lbl)
	}
}

到此這篇關(guān)于golang獲取prometheus數(shù)據(jù)(prometheus/client_golang包)的文章就介紹到這了,更多相關(guān)golang獲取prometheus內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • Golang?Makefile示例深入講解使用

    Golang?Makefile示例深入講解使用

    一次偶然的機(jī)會(huì),在?github?上看到有人用?Makefile,就嘗試了一下,發(fā)現(xiàn)真的非常合適,Makefile?本身就是用來描述依賴的,可讀性非常好,而且與強(qiáng)大的?shell?結(jié)合在一起,基本可以實(shí)現(xiàn)任何想要的功能
    2023-01-01
  • golang根據(jù)URL獲取文件名的示例代碼

    golang根據(jù)URL獲取文件名的示例代碼

    這篇文章主要為大家詳細(xì)介紹了golang根據(jù)URL獲取文件名,文中的示例代碼講解詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-01-01
  • 在go中進(jìn)行單元測(cè)試的案例分享

    在go中進(jìn)行單元測(cè)試的案例分享

    這篇文章主要介紹了使用Go進(jìn)行單元測(cè)試的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-01-01
  • Golang極簡入門教程(三):并發(fā)支持

    Golang極簡入門教程(三):并發(fā)支持

    這篇文章主要介紹了Golang極簡入門教程(三):并發(fā)支持,本文講解了goroutine線程、channel 操作符等內(nèi)容,需要的朋友可以參考下
    2014-10-10
  • go code review 代碼調(diào)試

    go code review 代碼調(diào)試

    這篇文章主要為大家介紹了go code review 代碼調(diào)試方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • GO語言常用的文件讀取方式

    GO語言常用的文件讀取方式

    這篇文章主要介紹了GO語言常用的文件讀取方式,涉及一次性讀取、分塊讀取與逐行讀取等方法,是非常實(shí)用的技巧,需要的朋友可以參考下
    2014-12-12
  • Go 數(shù)據(jù)結(jié)構(gòu)之堆排序示例詳解

    Go 數(shù)據(jù)結(jié)構(gòu)之堆排序示例詳解

    這篇文章主要為大家介紹了Go 數(shù)據(jù)結(jié)構(gòu)之堆排序示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-08-08
  • Go 代碼生成工具詳解

    Go 代碼生成工具詳解

    這篇文章主要介紹了Go 代碼生成工具詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-03-03
  • xorm根據(jù)數(shù)據(jù)庫生成go model文件的操作

    xorm根據(jù)數(shù)據(jù)庫生成go model文件的操作

    這篇文章主要介紹了xorm根據(jù)數(shù)據(jù)庫生成go model文件的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • SpringEvent優(yōu)雅解耦時(shí)連續(xù)兩個(gè)bug的解決方案

    SpringEvent優(yōu)雅解耦時(shí)連續(xù)兩個(gè)bug的解決方案

    這篇文章主要為大家介紹了SpringEvent優(yōu)雅解耦時(shí)連續(xù)兩個(gè)bug的解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-12-12

最新評(píng)論