• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    golang获取prometheus数据(prometheus/client_golang包)

    发布者: 娅水9213 | 发布时间: 2025-8-14 06:26| 查看数: 113| 评论数: 0|帖子模式

    1. 创建链接


    1.1 语法


    • 语法
    1. func NewClient(cfg Config) (Client, error)
    复制代码

    • 结构体
    1. type Config struct {
    2.     Address      string
    3.     Client       *http.Client
    4.     RoundTripper http.RoundTripper
    5. }
    复制代码

    • 示例
    1.         client, err = api.NewClient(api.Config{
    2.                 Address: "http://10.10.182.112:9090",
    3.         })
    复制代码
    1.2 完整示例
    1. package mainimport (        "fmt"        "github.com/prometheus/client_golang/api")func CreatClient() (client api.Client, err error) {        client, err = api.NewClient(api.Config{
    2.                 Address: "http://10.10.182.112:9090",
    3.         })        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创建成功")        }}
    复制代码
    2. 简单查询


    2.1 语法


    • 创建API实例
    1. func NewAPI(c Client) API
    复制代码

    • 查询
    1. func (API) Query(ctx context.Context, query string, ts time.Time, opts ...Option) (Value, Warnings, error)
    复制代码

    • 在context中设置超时
    1. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
    复制代码

    • 语法示例
    1.         v1api := proV1.NewAPI(Client)
    2.         ctx := context.Background()
    3.         result, warnings, err := v1api.Query(ctx, "up", time.Now(), proV1.WithTimeout(5*time.Second))
    复制代码
    2.2 完整示例
    1. package main

    2. import (
    3.         "context"
    4.         "fmt"
    5.         "github.com/prometheus/client_golang/api"
    6.         proV1 "github.com/prometheus/client_golang/api/prometheus/v1"
    7.         "github.com/prometheus/common/model"
    8.         "time"
    9. )

    10. var Client api.Client

    11. func init() {
    12.         Client, _ = CreatClient()
    13. }

    14. func CreatClient() (client api.Client, err error) {
    15.         client, err = api.NewClient(api.Config{
    16.                 Address: "http://10.10.181.112:9090",
    17.         })
    18.         if err != nil {
    19.                 fmt.Printf("Error creating client: %v\n", err)
    20.                 return nil, err
    21.         }
    22.         return client, nil
    23. }

    24. func Query() (result model.Value, err error) {
    25.         v1api := proV1.NewAPI(Client)
    26.         ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    27.         defer cancel()
    28.         result, warnings, err := v1api.Query(ctx, "up", time.Now(), proV1.WithTimeout(5*time.Second))
    29.         if err != nil {
    30.                 return nil, err
    31.         }
    32.         if len(warnings) > 0 {
    33.                 fmt.Printf("Warnings: %v\n", warnings)
    34.         }
    35.         return result, nil
    36. }

    37. func main() {
    38.         result, err := Query()
    39.         if err != nil {
    40.                 fmt.Errorf("%q", err)
    41.         }
    42.         fmt.Printf("Result:\n%v\n", result)
    43. }
    复制代码
    3. 范围值查询


    3.1 语法


    • 范围设置
    1. type Range struct {
    2.     Start, End time.Time
    3.     Step       time.Duration
    4. }
    复制代码
    语法示例
    1.         r := proV1.Range{
    2.                 Start: time.Now().Add(-time.Hour),
    3.                 End:   time.Now(),
    4.                 Step:  time.Minute,
    5.         }
    复制代码

    • 范围查询
    1. func (API) QueryRange(ctx context.Context, query string, r Range, opts ...Option) (Value, Warnings, error)
    复制代码
    语法示例
    1. result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r, proV1.WithTimeout(5*time.Second))
    复制代码
    3.2 完整示例
    1. package mainimport (        "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.Clientfunc 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{
    2.                 Start: time.Now().Add(-time.Hour),
    3.                 End:   time.Now(),
    4.                 Step:  time.Minute,
    5.         }        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. 获取指标名称和标签


    4.1 语法


    • 语法
    1. func (API) Series(ctx context.Context, matches []string, startTime time.Time, endTime time.Time) ([]model.LabelSet, Warnings, error)
    复制代码

    • 语法示例
    1.         lbls, warnings, err := v1api.Series(ctx, []string{
    2.                 "{__name__=~".+",job="prometheus"}",
    3.         }, time.Now().Add(-time.Hour), time.Now())
    复制代码
    说明:

    • 数组里可以写多条
      1. __name__
      复制代码
      表示指标名,等号后边支持正则匹配。
    • 后边可以接一些label,同样支持正则。
    比如示例中的
    1. job="prometheus"
    复制代码
    ,是我们在prometheus配置文件里写的job名。

    • LabelSet
    1. type LabelSet map[LabelName]LabelValue
    复制代码
    可以看到LabelSet实际是一个map,因此我们可以只打印示例中的指标名:
    1.         for _, lbl := range lbls {
    2.                 fmt.Println(lbl["__name__"])
    3.         }
    复制代码
    4.1 完整示例(获取所有数据条目)
    1. package main

    2. import (
    3.         "context"
    4.         "fmt"
    5.         "os"
    6.         "time"

    7.         "github.com/prometheus/client_golang/api"
    8.         proV1 "github.com/prometheus/client_golang/api/prometheus/v1"
    9. )

    10. var Client api.Client

    11. func init() {
    12.         Client, _ = CreatClient()
    13. }

    14. func CreatClient() (client api.Client, err error) {
    15.         client, err = api.NewClient(api.Config{
    16.                 Address: "http://10.10.181.112:9090",
    17.         })
    18.         if err != nil {
    19.                 fmt.Printf("Error creating client: %v\n", err)
    20.                 return nil, err
    21.         }
    22.         return client, nil
    23. }

    24. func ExampleAPI_series() {
    25.         v1api := proV1.NewAPI(Client)
    26.         ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    27.         defer cancel()
    28.         lbls, warnings, err := v1api.Series(ctx, []string{
    29.                 //"{__name__=~"scrape_.+",job="node"}",
    30.                 "{__name__=~".+"}",
    31.         }, time.Now().Add(-time.Hour), time.Now())
    32.         if err != nil {
    33.                 fmt.Printf("Error querying Prometheus: %v\n", err)
    34.                 os.Exit(1)
    35.         }
    36.         if len(warnings) > 0 {
    37.                 fmt.Printf("Warnings: %v\n", warnings)
    38.         }
    39.         fmt.Println("Result:", len(lbls))
    40.         for _, lbl := range lbls {
    41.                 //fmt.Println(lbl["__name__"])
    42.                 fmt.Println(lbl)
    43.         }
    44. }
    45. func main() {
    46.         ExampleAPI_series()
    47. }
    复制代码
    【附官方示例】

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

    2. import (
    3.         "context"
    4.         "fmt"
    5.         "net/http"
    6.         "os"
    7.         "time"

    8.         "github.com/prometheus/common/config"

    9.         "github.com/prometheus/client_golang/api"
    10.         v1 "github.com/prometheus/client_golang/api/prometheus/v1"
    11. )

    12. func ExampleAPI_query() {
    13.         client, err := api.NewClient(api.Config{
    14.                 Address: "http://demo.robustperception.io:9090",
    15.         })
    16.         if err != nil {
    17.                 fmt.Printf("Error creating client: %v\n", err)
    18.                 os.Exit(1)
    19.         }

    20.         v1api := v1.NewAPI(client)
    21.         ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    22.         defer cancel()
    23.         result, warnings, err := v1api.Query(ctx, "up", time.Now(), v1.WithTimeout(5*time.Second))
    24.         if err != nil {
    25.                 fmt.Printf("Error querying Prometheus: %v\n", err)
    26.                 os.Exit(1)
    27.         }
    28.         if len(warnings) > 0 {
    29.                 fmt.Printf("Warnings: %v\n", warnings)
    30.         }
    31.         fmt.Printf("Result:\n%v\n", result)
    32. }

    33. func ExampleAPI_queryRange() {
    34.         client, err := api.NewClient(api.Config{
    35.                 Address: "http://demo.robustperception.io:9090",
    36.         })
    37.         if err != nil {
    38.                 fmt.Printf("Error creating client: %v\n", err)
    39.                 os.Exit(1)
    40.         }

    41.         v1api := v1.NewAPI(client)
    42.         ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    43.         defer cancel()
    44.         r := v1.Range{
    45.                 Start: time.Now().Add(-time.Hour),
    46.                 End:   time.Now(),
    47.                 Step:  time.Minute,
    48.         }
    49.         result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r, v1.WithTimeout(5*time.Second))
    50.         if err != nil {
    51.                 fmt.Printf("Error querying Prometheus: %v\n", err)
    52.                 os.Exit(1)
    53.         }
    54.         if len(warnings) > 0 {
    55.                 fmt.Printf("Warnings: %v\n", warnings)
    56.         }
    57.         fmt.Printf("Result:\n%v\n", result)
    58. }

    59. type userAgentRoundTripper struct {
    60.         name string
    61.         rt   http.RoundTripper
    62. }

    63. // RoundTrip implements the http.RoundTripper interface.
    64. func (u userAgentRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
    65.         if r.UserAgent() == "" {
    66.                 // The specification of http.RoundTripper says that it shouldn't mutate
    67.                 // the request so make a copy of req.Header since this is all that is
    68.                 // modified.
    69.                 r2 := new(http.Request)
    70.                 *r2 = *r
    71.                 r2.Header = make(http.Header)
    72.                 for k, s := range r.Header {
    73.                         r2.Header[k] = s
    74.                 }
    75.                 r2.Header.Set("User-Agent", u.name)
    76.                 r = r2
    77.         }
    78.         return u.rt.RoundTrip(r)
    79. }

    80. func ExampleAPI_queryRangeWithUserAgent() {
    81.         client, err := api.NewClient(api.Config{
    82.                 Address:      "http://demo.robustperception.io:9090",
    83.                 RoundTripper: userAgentRoundTripper{name: "Client-Golang", rt: api.DefaultRoundTripper},
    84.         })
    85.         if err != nil {
    86.                 fmt.Printf("Error creating client: %v\n", err)
    87.                 os.Exit(1)
    88.         }

    89.         v1api := v1.NewAPI(client)
    90.         ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    91.         defer cancel()
    92.         r := v1.Range{
    93.                 Start: time.Now().Add(-time.Hour),
    94.                 End:   time.Now(),
    95.                 Step:  time.Minute,
    96.         }
    97.         result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)
    98.         if err != nil {
    99.                 fmt.Printf("Error querying Prometheus: %v\n", err)
    100.                 os.Exit(1)
    101.         }
    102.         if len(warnings) > 0 {
    103.                 fmt.Printf("Warnings: %v\n", warnings)
    104.         }
    105.         fmt.Printf("Result:\n%v\n", result)
    106. }

    107. func ExampleAPI_queryRangeWithBasicAuth() {
    108.         client, err := api.NewClient(api.Config{
    109.                 Address: "http://demo.robustperception.io:9090",
    110.                 // We can use amazing github.com/prometheus/common/config helper!
    111.                 RoundTripper: config.NewBasicAuthRoundTripper("me", "defintely_me", "", api.DefaultRoundTripper),
    112.         })
    113.         if err != nil {
    114.                 fmt.Printf("Error creating client: %v\n", err)
    115.                 os.Exit(1)
    116.         }

    117.         v1api := v1.NewAPI(client)
    118.         ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    119.         defer cancel()
    120.         r := v1.Range{
    121.                 Start: time.Now().Add(-time.Hour),
    122.                 End:   time.Now(),
    123.                 Step:  time.Minute,
    124.         }
    125.         result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)
    126.         if err != nil {
    127.                 fmt.Printf("Error querying Prometheus: %v\n", err)
    128.                 os.Exit(1)
    129.         }
    130.         if len(warnings) > 0 {
    131.                 fmt.Printf("Warnings: %v\n", warnings)
    132.         }
    133.         fmt.Printf("Result:\n%v\n", result)
    134. }

    135. func ExampleAPI_queryRangeWithAuthBearerToken() {
    136.         client, err := api.NewClient(api.Config{
    137.                 Address: "http://demo.robustperception.io:9090",
    138.                 // We can use amazing github.com/prometheus/common/config helper!
    139.                 RoundTripper: config.NewAuthorizationCredentialsRoundTripper("Bearer", "secret_token", api.DefaultRoundTripper),
    140.         })
    141.         if err != nil {
    142.                 fmt.Printf("Error creating client: %v\n", err)
    143.                 os.Exit(1)
    144.         }

    145.         v1api := v1.NewAPI(client)
    146.         ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    147.         defer cancel()
    148.         r := v1.Range{
    149.                 Start: time.Now().Add(-time.Hour),
    150.                 End:   time.Now(),
    151.                 Step:  time.Minute,
    152.         }
    153.         result, warnings, err := v1api.QueryRange(ctx, "rate(prometheus_tsdb_head_samples_appended_total[5m])", r)
    154.         if err != nil {
    155.                 fmt.Printf("Error querying Prometheus: %v\n", err)
    156.                 os.Exit(1)
    157.         }
    158.         if len(warnings) > 0 {
    159.                 fmt.Printf("Warnings: %v\n", warnings)
    160.         }
    161.         fmt.Printf("Result:\n%v\n", result)
    162. }

    163. func ExampleAPI_series() {
    164.         client, err := api.NewClient(api.Config{
    165.                 Address: "http://demo.robustperception.io:9090",
    166.         })
    167.         if err != nil {
    168.                 fmt.Printf("Error creating client: %v\n", err)
    169.                 os.Exit(1)
    170.         }

    171.         v1api := v1.NewAPI(client)
    172.         ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    173.         defer cancel()
    174.         lbls, warnings, err := v1api.Series(ctx, []string{
    175.                 "{__name__=~"scrape_.+",job="node"}",
    176.                 "{__name__=~"scrape_.+",job="prometheus"}",
    177.         }, time.Now().Add(-time.Hour), time.Now())
    178.         if err != nil {
    179.                 fmt.Printf("Error querying Prometheus: %v\n", err)
    180.                 os.Exit(1)
    181.         }
    182.         if len(warnings) > 0 {
    183.                 fmt.Printf("Warnings: %v\n", warnings)
    184.         }
    185.         fmt.Println("Result:")
    186.         for _, lbl := range lbls {
    187.                 fmt.Println(lbl)
    188.         }
    189. }
    复制代码
    到此这篇关于golang获取prometheus数据(prometheus/client_golang包)的文章就介绍到这了,更多相关golang获取prometheus内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    来源:互联网
    免责声明:如果侵犯了您的权益,请联系站长(1277306191@qq.com),我们会及时删除侵权内容,谢谢合作!

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表