...
1# gin-metrics
2gin-gonic/gin metrics exporter for Prometheus.
3
4
5## Introduction
6
7`gin-metrics` 为 gin HTTP 服务定义了一些监控指标,开箱即用。下边是默认监控指标的详细描述:
8
9
10| Metric | Type | Description |
11| ----------------------- | --------- | --------------------------------------------------- |
12| gin_request_total | Counter | 服务接收到的请求总数 |
13| gin_request_uv | Counter | 服务接收到的 IP 总数 |
14| gin_uri_request_total | Counter | 每个 URI 接收到的服务请求数 |
15| gin_request_body_total | Counter | 服务接收到的请求量,单位: 字节 |
16| gin_response_body_total | Counter | 服务返回的请求量,单位: 字节 |
17| gin_request_duration | Histogram | 服务处理请求使用的时间 |
18| gin_slow_request_total | Counter | 服务接收到的慢请求计数 |
19
20
21## Installation
22
23```bash
24$ go get github.com/penglongli/gin-metrics
25```
26
27## Usage
28
29使用如下代码运行,访问:`http://localhost:8080/metrics` 即可看到暴露出来的监控指标
30
31```go
32package main
33
34import (
35 "github.com/gin-gonic/gin"
36
37 "github.com/penglongli/gin-metrics/ginmetrics"
38)
39
40func main() {
41 r := gin.Default()
42
43 // get global Monitor object
44 m := ginmetrics.GetMonitor()
45
46 // +optional set metric path, default /debug/metrics
47 m.SetMetricPath("/metrics")
48 // +optional set slow time, default 5s
49 m.SetSlowTime(10)
50 // +optional set request duration, default {0.1, 0.3, 1.2, 5, 10}
51 // used to p95, p99
52 m.SetDuration([]float64{0.1, 0.3, 1.2, 5, 10})
53
54 // set middleware for gin
55 m.Use(r)
56
57 r.GET("/product/:id", func(ctx *gin.Context) {
58 "productId": ctx.Param("id"),
59 })
60 })
61 _ = r.Run()
62}
63
64```
65
66## Custom Metric
67
68`gin-metric` 提供了自定义监控指标的使用方式
69
70### Gauge
71
72使用 `Gauge` 类型监控指标,可以通过 3 种方法来修改监控值:`SetGaugeValue`、`Inc`、`Add`
73
74首先,需要定义一个 `Gauge` 类型的监控指标:
75
76```go
77gaugeMetric := &ginmetrics.Metric{
78 Type: ginmetrics.Gauge,
79 Name: "example_gauge_metric",
80 Description: "an example of gauge type metric",
81 Labels: []string{"label1"},
82}
83
84// Add metric to global monitor object
85_ = ginmetrics.GetMonitor().AddMetric(gaugeMetric)
86```
87
88**SetGaugeValue**
89
90`SetGaugeValue` 方法会直接设置监控指标的值
91
92```go
93_ = ginmetrics.GetMonitor().GetMetric("example_gauge_metric").SetGaugeValue([]string{"label_value1"}, 0.1)
94```
95
96**Inc**
97
98`Inc` 方法会在监控指标值的基础上增加 1
99
100```go
101_ = ginmetrics.GetMonitor().GetMetric("example_gauge_metric").Inc([]string{"label_value1"})
102```
103
104**Add**
105
106`Add` 方法会为监控指标增加传入的值
107
108```go
109_ = ginmetrics.GetMonitor().GetMetric("example_gauge_metric").Add([]string{"label_value1"}, 0.2)
110```
111
112### Counter
113
114`Counter` 类型的监控指标,可以使用 `Inc` 和 `Add` 方法,但是不能使用 `SetGaugeValue` 方法
115
116
117### Histogram and Summary
118
119对于 `Histogram` 和 `Summary` 类型的监控指标,需要用 `Observe` 方法来设置监控值。
120
121## Contributing
122
123如果有遇见什么问题,或者需要修改,可以 [新建 ISSUE](https://github.com/penglongli/gin-metrics/issues/new)
124或者 [新建 PullRequest](https://github.com/penglongli/gin-metrics/pulls).
125
View as plain text