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

2025-03-02 17:50

本文主要是介绍golang获取prometheus数据(prometheus/client_golang包),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《golang获取prometheus数据(prometheus/client_golang包)》本文主要介绍了使用Go语言的prometheus/client_golang包来获取Prometheu...

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: %v\n", err)
		retChina编程urn 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实例
func NewAPI(c Client) API
  • 查询
func (API) Query(ctx context.Context, query string, ts time.Time, opts ...Option) (Value, Warnings, error)
  • 在context中设置超时
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 语法

  • 范围设置
type Range struct {
    Start, End time.Time
    Step       time.Duration
}

语法示例

	r := proV1.Range{
		Start: time.Now().Apythondd(-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",
	})
	ifjs 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. 获取指标名称和标签

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

说明:

  • 数组里可以写多条
  • __name__ 表示指标名,等号后边支持正则匹配。
  • 后边可以接一些label,同样支持正则。

比如示例中的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: %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)
	}
}

到此这篇关于golang获取prometheus数据(prometheus/client_golang包)的文章就介绍到这了,更多相关golang获取prometheus内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)! 

这篇关于golang获取prometheus数据(prometheus/client_golang包)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:http://www.cppcns.com/jiaoben/golang/702472.html
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1153609

相关文章

解决mysql插入数据锁等待超时报错:Lock wait timeout exceeded;try restarting transaction

《解决mysql插入数据锁等待超时报错:Lockwaittimeoutexceeded;tryrestartingtransaction》:本文主要介绍解决mysql插入数据锁等待超时报... 目录报错信息解决办法1、数据库中执行如下sql2、再到 INNODB_TRX 事务表中查看总结报错信息Lock

使用C#删除Excel表格中的重复行数据的代码详解

《使用C#删除Excel表格中的重复行数据的代码详解》重复行是指在Excel表格中完全相同的多行数据,删除这些重复行至关重要,因为它们不仅会干扰数据分析,还可能导致错误的决策和结论,所以本文给大家介绍... 目录简介使用工具C# 删除Excel工作表中的重复行语法工作原理实现代码C# 删除指定Excel单元

Linux lvm实例之如何创建一个专用于MySQL数据存储的LVM卷组

《Linuxlvm实例之如何创建一个专用于MySQL数据存储的LVM卷组》:本文主要介绍使用Linux创建一个专用于MySQL数据存储的LVM卷组的实例,具有很好的参考价值,希望对大家有所帮助,... 目录在Centos 7上创建卷China编程组并配置mysql数据目录1. 检查现有磁盘2. 创建物理卷3. 创

Nacos日志与Raft的数据清理指南

《Nacos日志与Raft的数据清理指南》随着运行时间的增长,Nacos的日志文件(logs/)和Raft持久化数据(data/protocol/raft/)可能会占用大量磁盘空间,影响系统稳定性,本... 目录引言1. Nacos 日志文件(logs/ 目录)清理1.1 日志文件的作用1.2 是否可以删除

使用Python获取JS加载的数据的多种实现方法

《使用Python获取JS加载的数据的多种实现方法》在当今的互联网时代,网页数据的动态加载已经成为一种常见的技术手段,许多现代网站通过JavaScript(JS)动态加载内容,这使得传统的静态网页爬取... 目录引言一、动态 网页与js加载数据的原理二、python爬取JS加载数据的方法(一)分析网络请求1

通过cmd获取网卡速率的代码

《通过cmd获取网卡速率的代码》今天从群里看到通过bat获取网卡速率两段代码,感觉还不错,学习bat的朋友可以参考一下... 1、本机有线网卡支持的最高速度:%v%@echo off & setlocal enabledelayedexpansionecho 代码开始echo 65001编码获取: >

golang float和科学计数法转字符串的实现方式

《golangfloat和科学计数法转字符串的实现方式》:本文主要介绍golangfloat和科学计数法转字符串的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望... 目录golang float和科学计数法转字符串需要对float转字符串做处理总结golang float

golang实现延迟队列(delay queue)的两种实现

《golang实现延迟队列(delayqueue)的两种实现》本文主要介绍了golang实现延迟队列(delayqueue)的两种实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的... 目录1 延迟队列:邮件提醒、订单自动取消2 实现2.1 simplChina编程e简单版:go自带的time

Golang实现Redis分布式锁(Lua脚本+可重入+自动续期)

《Golang实现Redis分布式锁(Lua脚本+可重入+自动续期)》本文主要介绍了Golang分布式锁实现,采用Redis+Lua脚本确保原子性,持可重入和自动续期,用于防止超卖及重复下单,具有一定... 目录1 概念应用场景分布式锁必备特性2 思路分析宕机与过期防止误删keyLua保证原子性可重入锁自动

golang 对象池sync.Pool的实现

《golang对象池sync.Pool的实现》:本文主要介绍golang对象池sync.Pool的实现,用于缓存和复用临时对象,以减少内存分配和垃圾回收的压力,下面就来介绍一下,感兴趣的可以了解... 目录sync.Pool的用法原理sync.Pool 的使用示例sync.Pool 的使用场景注意sync.