gmetrics

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 11 Imported by: 0

README

Introduction

gmetrics是对gin接入Prometheus的封装

默认记录gin http server的指标,支持传入自定义指标,自定义处理函数

Default Metrics

Name Type Labels Exposed Information
gin_request_uv Counter {"host"} all the server received ip num
gin_request_total Counter {"uri", "method", "code"} all the server received request num with every uri
gin_request_body_total Counter nil the server received request body size, unit byte
gin_response_body_total Counter nil the server send response body size, unit byte
gin_request_duration Histogram {"uri", "method"} the time server took to handle the request

Usage

四种指标类型及对应操作

Counter:Inc、Add

Gauge:Inc、Add、Set

Histogram:Observe

Summary:Observe

option

WithCloseDefault:关闭默认指标

WithExtraMetricHandle:扩展gin中间件自定义metrics处理

WithMetricPath: 定义metrics访问路径

WithReqDuration:定义gin_request_duration请求时间统计维度,[]float64{0.1, 0.5, 1, 5}

WithExcludeFn:过滤掉不需要的path

WithBloomFilter:自定义统计uv的BloomFilter,默认内存版,多实例可使用Redis版(需要注意清理),不统计传入nil

实例

中间件使用见 example 内

import  "github.com/SigmaGavin/slardar/pkg/gmetrics"

......
got, err := gmetrics.NewMonitor("nameSpace", nil) // 初始化metrics
if err != nil {
	log.Fatal(err)
}
r := gin.Default()
err = got.Use(r) // 注册自定义metrics路由
if err != nil {
	log.Fatal(err)
}
......

Grafana

提供默认的图标供参考,可以修改配置导入使用。

接入参考:

替换配置json中的metrics名称,主要为命名空间的替换,如dap_gin_request_total --> {{yours namespace}}_gin_request_total,名字替换完成后,在grafana中导入配置,即可显示指标看板。

image-20220523154004290

参考的grafana图表,Grafana configuration

grafana1

grafana2

grafana3

grafana4

AlertManager

告警等级示例

  • warning
  • critical

告警规则示例

通用规则(对于默认指标的告警规则)

名称 等级 告警持续时间 统计时长 阈值 描述
dap-up critical for 1m - - 服务是否启动
dap-qps warning for 1m 过去1m 500 服务QPS过高
dap-latency critical for 30s 过去1m 3s 服务p99延迟过高
dap-goroutione warning for 30s - 500 服务协程数过高
dap-http-code critical for 1m 过去1m 10% 服务http返回状态码错误率过高

业务规则(根据业务自定义的指标的告警规则)

名称 等级 告警持续时间 统计时长 阈值 描述
dap-biz-code critical for 1m 过去1m 10% 服务业务返回状态码错误率过高
dap-mongo-error critical for 1m 过去1m 10% 服务操作mongo错误率过高
......

接入参考:

告警rule文件中修改alert告警规则:

替换alert.expr指标名称,如dap_gin_request_total --> {{yours namespace}}_gin_request_total;

修改group.name和alert.team名称,与运维确定告警所需要的label;

将告警规则文件和飞书群ID给到运维进行配置。

参考的告警规则,Alert rule

alert1

alert2

alert3

Documentation

Index

Constants

View Source
const (
	KB uint64 = 1 << (10 * iota)
	MB
	GB
	TB
	PB
	EB
)

https://www.socketloop.com/tutorials/golang-how-to-declare-kilobyte-megabyte-gigabyte-terabyte-and-so-on

Variables

This section is empty.

Functions

This section is empty.

Types

type BloomFilter

type BloomFilter interface {
	Add(value string)
	Contains(value string) bool
}

BloomFilter is interface for bloom filter

func NewBloomFilter

func NewBloomFilter() BloomFilter

NewBloomFilter creates a single bloomFilter.

type ExtraMetricHandleFn

type ExtraMetricHandleFn func(c *gin.Context, m *Monitor, start time.Time)

ExtraMetricHandleFn Handle extra metrics

type Metric

type Metric struct {
	Type        MetricType
	NameSpace   string
	Name        string
	Description string
	Labels      []string
	ConstLabels map[string]string
	Buckets     []float64
	Objectives  map[float64]float64
	// contains filtered or unexported fields
}

Metric defines a metric object. Users can use it to save metric data. Every metric should be globally unique by name.

func (*Metric) Add

func (m *Metric) Add(labelValues []string, value float64) error

Add adds the given value to the Metric object. Only for Counter/Gauge type metric.

func (*Metric) Inc

func (m *Metric) Inc(labelValues []string) error

Inc increases value for Counter/Gauge type metric, increments the counter by 1

func (*Metric) Observe

func (m *Metric) Observe(labelValues []string, value float64) error

Observe is used by Histogram and Summary type metric to add observations.

func (*Metric) Set

func (m *Metric) Set(labelValues []string, value float64) error

Set set the given value to the Metric object. Only for Gauge type metric.

type MetricType

type MetricType int

MetricType is the type of metric

const (
	// None .
	None MetricType = iota
	// Counter is a cumulative metric.
	Counter
	// Gauge is a metric that represents a single numerical value that can arbitrarily go up and down.
	Gauge
	// Histogram is samples observations and counts them in configurable buckets.
	Histogram
	// Summary samples observations.
	Summary
)

type Monitor

type Monitor struct {
	// contains filtered or unexported fields
}

Monitor is an object that uses to set gin server monitor.

func NewMonitor

func NewMonitor(nameSpace string, metrics []*Metric, opts ...Option) (*Monitor, error)

NewMonitor create a new monitor.

func (*Monitor) AddMetric

func (m *Monitor) AddMetric(metric *Metric) error

AddMetric add custom monitor metric.

func (*Monitor) AddMetrics

func (m *Monitor) AddMetrics(metrics []*Metric) error

AddMetrics add custom monitor metrics.

func (*Monitor) AddRawMetric

func (m *Monitor) AddRawMetric(name string, ty MetricType, metric prometheus.Collector) error

AddRawMetric add raw monitor metric.

func (*Monitor) GetMetric

func (m *Monitor) GetMetric(name string) *Metric

GetMetric used to get metric object by metric_name.

func (*Monitor) GetRawMetric

func (m *Monitor) GetRawMetric(name string) prometheus.Collector

GetRawMetric used to get raw metric object by metric_name.

func (*Monitor) Use

func (m *Monitor) Use(r *gin.Engine) error

Use set gin metrics middleware

type Option

type Option func(*options)

Option is the options for gmetrics

func WithBloomFilter

func WithBloomFilter(bloomFilter BloomFilter) Option

WithBloomFilter is the bloom filter of the uv metrics, set nil close uv metrics.

func WithCloseDefault

func WithCloseDefault(closeDefault bool) Option

WithCloseDefault set the default metrics close

func WithExcludeFn

func WithExcludeFn(excludeFn RequestExcludeFn) Option

WithExcludeFn is to exclude func of the metrics

func WithExtraMetricHandle

func WithExtraMetricHandle(extraMetricHandle ExtraMetricHandleFn) Option

WithExtraMetricHandle is adding extra metric handle

func WithMetricPath

func WithMetricPath(path string) Option

WithMetricPath is the path of the metrics

func WithReqDuration

func WithReqDuration(duration []float64) Option

WithReqDuration is the duration of the metrics

type RequestExcludeFn

type RequestExcludeFn func(c *gin.Context) bool

RequestExcludeFn Exclude requests that are not counted

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL