欢迎加入go语言学习交流群 636728449

Prometheus笔记(二)监控go项目实时给grafana展示

Prometheus笔记(一)metric type

Prometheus笔记(一)metric type

Prometheus客户端库提供四种核心度量标准类型。 这些目前仅在客户端库中区分(以启用针对特定类型的使用而定制的API)和有线协议。 Prometheus服务器尚未使用类型信息,并将所有数据展平为无类型时间序列。(本文所有示例代码都是使用go来举例的)

1、Counter

计数器是表示单个单调递增计数器的累积量,其值只能增加或在重启时重置为零。 例如,您可以使用计数器来表示服务的总请求数,已完成的任务或错误总数。 不要使用计数器来监控可能减少的值。 例如,不要使用计数器来处理当前正在运行的进程数,而应该用Gauge。

counter主要有两个方法:

//将counter值加1.
Inc()
// 将指定值加到counter值上,如果指定值< 0会panic.
Add(float64)

1.1 Counter

一般 metric 容器使用的步骤都是:

​ 1、初始化一个metric容器

​ 2、Register注册容器

​ 3、向容器中添加值

使用举例:

//step1:初始一个counter
pushCounter := prometheus.NewCounter(prometheus.CounterOpts{
Name: "repository_pushes", // 注意: 没有help字符串
})
err := prometheus.Register(pushCounter) // 会返回一个错误.
if err != nil {
fmt.Println("Push counter couldn't be registered, no counting will happen:", err)
return
} // Try it once more, this time with a help string.
pushCounter = prometheus.NewCounter(prometheus.CounterOpts{
Name: "repository_pushes",
Help: "Number of pushes to external repository.",
}) //setp2: 注册容器
err = prometheus.Register(pushCounter)
if err != nil {
fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err)
return
} pushComplete := make(chan struct{})
// TODO: Start a goroutine that performs repository pushes and reports
// each completion via the channel.
for range pushComplete {
//step3:向容器中写入值
pushCounter.Inc()
}

输出:

Push counter couldn't be registered, no counting will happen: descriptor Desc{fqName: "repository_pushes", help: "", constLabels: {}, variableLabels: []} is invalid: empty help string

1.2 CounterVec

CounterVec是一组counter,这些计数器具有相同的描述,但它们的变量标签具有不同的值。 如果要计算按各种维度划分的相同内容(例如,响应代码和方法分区的HTTP请求数),则使用此方法。使用NewCounterVec创建实例。

//step1:初始化一个容器
httpReqs := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
},
[]string{"code", "method"},
)
//step2:注册容器
prometheus.MustRegister(httpReqs) httpReqs.WithLabelValues("404", "POST").Add(42) // If you have to access the same set of labels very frequently, it
// might be good to retrieve the metric only once and keep a handle to
// it. But beware of deletion of that metric, see below!
//step3:向容器中写入值,主要调用容器的方法如Inc()或者Add()方法
m := httpReqs.WithLabelValues("200", "GET")
for i := 0; i < 1000000; i++ {
m.Inc()
}
// Delete a metric from the vector. If you have previously kept a handle
// to that metric (as above), future updates via that handle will go
// unseen (even if you re-create a metric with the same label set
// later).
httpReqs.DeleteLabelValues("200", "GET")
// Same thing with the more verbose Labels syntax.
httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"})

2、Gauge

2.1 Gauge

Gauge可以用来存放一个可以任意变大变小的数值,通常用于测量值,例如温度或当前内存使用情况,或者运行的goroutine数量

主要有以下四个方法

// 将Gauge中的值设为指定值.
Set(float64)
// 将Gauge中的值加1.
Inc()
// 将Gauge中的值减1.
Dec()
// 将指定值加到Gauge中的值上。(指定值可以为负数)
Add(float64)
// 将指定值从Gauge中的值减掉。(指定值可以为负数)
Sub(float64)

示例代码(实时统计CPU的温度):

//step1:初始化容器
cpuTemprature := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "CPU_Temperature",
Help: "the temperature of CPU",
})
//step2:注册容器
prometheus.MustRegister(cpuTemprature)
//定时获取cpu温度并且写入到容器
func(){
tem = getCpuTemprature()
//step3:向容器中写入值。调用容器的方法
cpuTemprature.Set(tem)
}

2.2 GaugeVec

假设你要一次性统计四个cpu的温度,这个时候就适合使用GaugeVec了。

cpusTemprature := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "CPUs_Temperature",
Help: "the temperature of CPUs.",
},
[]string{
// Which cpu temperature?
"cpuName",
},
)
prometheus.MustRegister(cpusTemprature) cpusTemprature.WithLabelValues("cpu1").Set(temperature1)
cpusTemprature.WithLabelValues("cpu2").Set(temperature2)
cpusTemprature.WithLabelValues("cpu3").Set(temperature3)

3、Summary

Summary从事件或样本流中捕获单个观察,并以类似于传统汇总统计的方式对其进行汇总:1。观察总和,2。观察计数,3。排名估计。典型的用例是观察请求延迟。 默认情况下,Summary提供延迟的中位数。

temps := prometheus.NewSummary(prometheus.SummaryOpts{
Name: "pond_temperature_celsius",
Help: "The temperature of the frog pond.",
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
}) // Simulate some observations.
for i := 0; i < 1000; i++ {
temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10)
} // Just for demonstration, let's check the state of the summary by
// (ab)using its Write method (which is usually only used by Prometheus
// internally).
metric := &dto.Metric{}
temps.Write(metric)
fmt.Println(proto.MarshalTextString(metric))

4、Histogram

主要用于表示一段时间范围内对数据进行采样,(通常是请求持续时间或响应大小),并能够对其指定区间以及总数进行统计,通常我们用它计算分位数的直方图。

temps := prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "pond_temperature_celsius",
Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells.
Buckets: prometheus.LinearBuckets(20, 5, 5), // 5 buckets, each 5 centigrade wide.
}) // Simulate some observations.
for i := 0; i < 1000; i++ {
temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10)
} // Just for demonstration, let's check the state of the histogram by
// (ab)using its Write method (which is usually only used by Prometheus
// internally).
metric := &dto.Metric{}
temps.Write(metric)
fmt.Println(proto.MarshalTextString(metric))

欢迎加入go语言学习交流群 636728449

二、参考资料

[1] https://godoc.org/github.com/prometheus/client_golang/prometheus

[2] https://prometheus.io/docs/introduction/overview/

Prometheus笔记(一)metric type的更多相关文章

  1. Prometheus笔记(二)监控go项目实时给grafana展示

    欢迎加入go语言学习交流群 636728449 Prometheus笔记(二)监控go项目实时给grafana展示 Prometheus笔记(一)metric type 文章目录 一.promethe ...

  2. prometheus 笔记

    前言 prometheus 是监控应用软件类似于nagios. 安装 1.官网下载prometheus-2.2.0.linux-amd64压缩包,解压,执行./prometheus即可.这里重要的是配 ...

  3. Qt笔记之Q_DECLARE_METATYPE(Type)

    首先看一看QVariant这个类,我们可以把它当做一个万能数据类型,需要的时候能转换为一种特定的类型. 使用canConvert()函数检查是否能转换为你想要的数据类型,结构为:bool QVaria ...

  4. MyBatis笔记----@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class

    使用MyBatis 3.4.1或者其以上版本 @Intercepts({ @Signature(type = StatementHandler.class,  method = "prepa ...

  5. go学习笔记-类型转换(Type Conversion)

    类型转换(Type Conversion) 类型转换用于将一种数据类型的变量转换为另外一种类型的变,基本格式 type_name(expression) type_name 为类型,expressio ...

  6. 笔记 Activator.CreateInstance(Type)

    这段代码取自NopCommerce 3.80 的 权限列表初始化代码 dynamic provider = Activator.CreateInstance(providerType);   文件位置 ...

  7. Prometheus 四种metric类型

    Prometheus的4种metrics(指标)类型: Counter Gauge Histogram Summary 四种指标类型的数据对象都是数字,如果要监控文本类的信息只能通过指标名称或者 la ...

  8. Prometheus监控学习笔记之全面学习Prometheus

    0x00 概述 Prometheus是继Kubernetes后第2个正式加入CNCF基金会的项目,容器和云原生领域事实的监控标准解决方案.在这次分享将从Prometheus的基础说起,学习和了解Pro ...

  9. prometheus client_golang使用

    序言 Prometheus是一个开源的监控系统,拥有许多Advanced Feature,他会定期用HTTP协议来pull所监控系统状态进行数据收集,在加上timestamp等数据组织成time se ...

随机推荐

  1. .net core 对象序列化为Json及Json反序列化关于DataContractJsonSerializer和Newtonsoft使用的完整案例,源码已更新至开源模板

    很多人告诉你怎么用,但是却不会告诉你用什么好.不知道在进行序列化和反序列化Json时用那个好,因为有太多选择,如.NET Framework下可以选DataContractJsonSerializer ...

  2. IP网段的判断

    一.    OSI七层模型 表示 说明 作用 应用层 HTTP.ftp 协议 表示层 UTF-8 将应用层协议翻译成计算机可识别的语言 会话层 管理传输层 传输层 TCP/UDP 建立以及断开连接 网 ...

  3. Hazel,自动整理文件,让你的 Mac 井井有条

    原文地址 https://sspai.com/post/35225 让我们从实际需求出发,看看问题出在哪里,并在此基础上认识和学习使用 Hazel. 电脑随着使用时间的增长,其中的文件也在疯狂的增长, ...

  4. [LC]88题 Merge Sorted Array (合并两个有序数组 )

    ①英文题目 Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. N ...

  5. 【Java】面向对象初探

    前段时间经历了一段心态浮躁期,这让我想起了自己最初的计划,要提升自己知识体系的广度.前几年一直做的是web前端这一块的工作,但我希望通过自己在学习Java这样的过程来提升自己的知识广度. 面向对象概述 ...

  6. 安卓JNI精细化讲解,让你彻底了解JNI(一):环境搭建与HelloWord

    目录 1.基础概念 ├──1.1.JNI ├──1.2.NDK ├──1.3.CMake与ndk-build 2.环境搭建 3.Native C++ 项目(HelloWord案例) ├── 3.1.项 ...

  7. 函数的prototype

    1.函数的prototype属性 每一个函数都有一个prototype属性,默认指向object空对象(原型对象),每一个原型对象都有一个constructor属性,指向函数对象 2.给原型对象添加属 ...

  8. bash:字符串变量查找

    提供了替换文本的查找替换功能,如 sed s/Wintel/Linux/g data (将Wintel替换为Linux)  大命令 下边是基于变量的小命令: 1)查找与替换 ${data/Wintel ...

  9. class继承关键字extends和super

    // 父类 class person { constructor (name,age) { this.name = name this.age = age } } class CheChinese e ...

  10. Hadoop简述

    Haddop是什么? Hadoop是一个由Apache基金会所开发的分布式系统基础架构 主要解决,海量数据的存储和海量数据的分析计算问题. Hadoop三大发行版本 Apache版本最原始(最基础)的 ...