-
Notifications
You must be signed in to change notification settings - Fork 6
/
metrics.go
513 lines (449 loc) · 17.1 KB
/
metrics.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package metrics
import (
"time"
"github.com/golang/protobuf/proto"
"github.com/povilasv/prommod"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promauto"
_err "github.com/romapres2010/goapp/pkg/common/error"
_log "github.com/romapres2010/goapp/pkg/common/logger"
)
const (
DEF_METRICS_NAMESPACE = "com"
DEF_METRICS_SUBSYSTEM = "api"
)
// Config конфигурационные настройки
type Config struct {
MetricsNamespace string `yaml:"metrics_namespace"`
MetricsSubsystem string `yaml:"metrics_subsystem"`
// Метрики DB
CollectDBCountVec bool `yaml:"collect_db_count_vec"`
CollectDBDurationVec bool `yaml:"collect_db_duration_vec"`
// Метрики HTTP request
CollectHTTPRequestsCountVec bool `yaml:"collect_http_requests_count_vec"`
CollectHTTPErrorRequestsCountVec bool `yaml:"collect_http_error_requests_count_vec"`
CollectHTTPRequestsDurationVec bool `yaml:"collect_http_requests_duration_vec"`
CollectHTTPActiveRequestsCount bool `yaml:"collect_http_active_requests_count"`
CollectHTTPRequestsDuration bool `yaml:"collect_http_requests_duration"`
// Метрики HTTP client call
CollectHTTPClientCallCountVec bool `yaml:"collect_http_client_call_count_vec"`
CollectHTTPClientCallDurationVec bool `yaml:"collect_http_client_call_duration_vec"`
// Метрики вычислений
CollectCalcCountVec bool `yaml:"collect_calc_count_vec"`
CollectCalcDurationVec bool `yaml:"collect_calc_duration_vec"`
// Метрики JSON
CollectMarshalingDurationVec bool `yaml:"collect_marshaling_duration_vec"`
CollectUnMarshalingDurationVec bool `yaml:"collect_un_marshaling_duration_vec"`
// Метрики WorkerPool
CollectWPTaskQueueBufferLenVec bool `yaml:"collect_wp_task_queue_buffer_len_vec"`
CollectWPAddTaskWaitCountVec bool `yaml:"collect_wp_add_task_wait_count_vec"`
CollectWPWorkerProcessCountVec bool `yaml:"collect_wp_worker_process_count_vec"`
CollectWPTaskProcessDurationVec bool `yaml:"collect_wp_task_process_duration_ms_by_name"`
}
type Metrics struct {
Cfg *Config
Registry *prometheus.Registry
// Метрики DB
DBCountVec *prometheus.CounterVec
DBDurationVec *prometheus.HistogramVec
// Метрики HTTP request
HTTPRequestsCountVec *prometheus.CounterVec
HTTPErrorRequestsCountVec *prometheus.CounterVec
HTTPRequestsDurationVec *prometheus.HistogramVec
HTTPActiveRequestsCount prometheus.Gauge
HTTPRequestsDuration prometheus.Histogram
// Метрики HTTP client call
HTTPClientCallCountVec *prometheus.CounterVec
HTTPClientCallDurationVec *prometheus.HistogramVec
// Метрики вычислений
CalcCountVec *prometheus.CounterVec
CalcDurationVec *prometheus.HistogramVec
// Метрики JSON
MarshalingDurationVec *prometheus.HistogramVec
UnMarshalingDurationVec *prometheus.HistogramVec
// Метрики WorkerPoolVec
WPTaskQueueBufferLenVec *prometheus.GaugeVec
WPAddTaskWaitCountVec *prometheus.GaugeVec
WPWorkerProcessCountVec *prometheus.GaugeVec
WPTaskProcessDurationVec *prometheus.HistogramVec
}
func New(cfg *Config) (*Metrics, error) {
_log.Info("Creating new metrics service")
{ // входные проверки
if cfg == nil {
return nil, _err.NewTyped(_err.ERR_INCORRECT_CALL_ERROR, _err.ERR_UNDEFINED_ID, "if cfg == nil {}").PrintfError()
}
} // входные проверки
if cfg.MetricsNamespace == "" {
cfg.MetricsNamespace = DEF_METRICS_NAMESPACE
}
if cfg.MetricsSubsystem == "" {
cfg.MetricsSubsystem = DEF_METRICS_SUBSYSTEM
}
var metrics = Metrics{}
metrics.Cfg = cfg
metrics.Registry = prometheus.NewRegistry()
// Add Go module build info.
metrics.Registry.MustRegister(collectors.NewBuildInfoCollector())
//metrics.Registry.MustRegister(collectors.NewGoCollector(
// collectors.WithGoCollections(collectors.GoRuntimeMemStatsCollection | collectors.GoRuntimeMetricsCollection),
//))
metrics.Registry.MustRegister(collectors.NewGoCollector(
collectors.WithGoCollectorRuntimeMetrics(),
))
// вывод в метрики всех зависимых модулей
err := metrics.Registry.Register(prommod.NewCollector("app_name"))
if err != nil {
return nil, err
}
_log.Info("Dependency: ", "\n"+prommod.Print("app_name"))
{ // Метрики DB
metrics.DBCountVec = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "db_total",
Help: "The total number of processed DB by sql statement",
},
[]string{"SQL"},
)
metrics.DBDurationVec = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "db_duration_ms",
Help: "The duration histogram of DB operation in ms by sql statement",
Buckets: []float64{0.01, 0.05, 0.10, 0.50, 1.00, 5.00, 10.00},
},
[]string{"SQL"},
)
metrics.Registry.MustRegister(metrics.DBCountVec)
metrics.Registry.MustRegister(metrics.DBDurationVec)
} // Метрики DB
{ // Метрики HTTP
metrics.HTTPRequestsCountVec = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "http_requests_total_by_resource",
Help: "How many HTTP requests processed, partitioned by resource",
},
[]string{"resource", "method"},
)
metrics.HTTPErrorRequestsCountVec = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "http_requests_error_total_by_resource",
Help: "How many HTTP requests was ERRORED, partitioned by resource",
},
[]string{"resource", "method"},
)
metrics.HTTPRequestsDurationVec = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "http_request_duration_ms_by_resource",
Help: "The duration histogram of HTTP requests in ms by resource",
Buckets: []float64{0.1, 5, 10, 50, 100, 500, 1000},
},
[]string{"resource", "method"},
)
metrics.HTTPActiveRequestsCount = promauto.NewGauge(
prometheus.GaugeOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "http_active_requests_count",
Help: "The total number of active HTTP requests",
})
metrics.HTTPRequestsDuration = promauto.NewHistogram(
prometheus.HistogramOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "http_request_duration_ms",
Help: "The duration histogram of HTTP requests in ms",
Buckets: []float64{0.1, 5, 10, 50, 100, 500, 1000},
})
metrics.Registry.MustRegister(metrics.HTTPRequestsCountVec)
metrics.Registry.MustRegister(metrics.HTTPErrorRequestsCountVec)
metrics.Registry.MustRegister(metrics.HTTPRequestsDurationVec)
metrics.Registry.MustRegister(metrics.HTTPActiveRequestsCount)
metrics.Registry.MustRegister(metrics.HTTPRequestsDuration)
} // Метрики HTTP
{ // Метрики HTTP client call
metrics.HTTPClientCallCountVec = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "http_client_call_total_by_resource",
Help: "How many HTTP client call processed, partitioned by resource",
},
[]string{"resource", "method"},
)
metrics.HTTPClientCallDurationVec = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "http_client_call_duration_ms_by_resource",
Help: "The duration histogram of HTTP client call in ms by resource",
Buckets: []float64{0.1, 5, 10, 50, 100, 500, 1000},
},
[]string{"resource", "method"},
)
metrics.Registry.MustRegister(metrics.HTTPClientCallCountVec)
metrics.Registry.MustRegister(metrics.HTTPClientCallDurationVec)
} // Метрики HTTP client call
{ // Метрики вычислений
metrics.CalcCountVec = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "calc_total_by_type",
Help: "How many calculation processed, partitioned by type",
},
[]string{"type"},
)
metrics.CalcDurationVec = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "calc_duration_by_type",
Help: "The duration histogram of calculation in ms by type",
Buckets: []float64{0.1, 5, 10, 50, 100, 500, 1000},
},
[]string{"type"},
)
metrics.Registry.MustRegister(metrics.CalcCountVec)
metrics.Registry.MustRegister(metrics.CalcDurationVec)
} // Метрики вычислений
{ // Метрики JSON
metrics.MarshalingDurationVec = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "json_marshaling_duration_by_type",
Help: "The duration histogram of JSON marshaling in ms by type",
Buckets: []float64{0.01, 0.05, 0.10, 0.50, 1.00, 5.00, 10.00},
},
[]string{"type"},
)
metrics.UnMarshalingDurationVec = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "json_unmarshaling_duration_by_type",
Help: "The duration histogram of JSON unmarshaling in ms by type",
Buckets: []float64{0.01, 0.05, 0.10, 0.50, 1.00, 5.00, 10.00},
},
[]string{"type"},
)
metrics.Registry.MustRegister(metrics.MarshalingDurationVec)
metrics.Registry.MustRegister(metrics.UnMarshalingDurationVec)
} // Метрики JSON
{ // Метрики WorkerPool
metrics.WPTaskQueueBufferLenVec = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "wp_task_queue_buffer_len_vec",
Help: "The len of the worker pool buffer",
},
[]string{"type"},
)
metrics.WPAddTaskWaitCountVec = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "wp_add_task_wait_count_vec",
Help: "The number of the task waiting to add to worker pool queue",
},
[]string{"type"},
)
metrics.WPWorkerProcessCountVec = promauto.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "wp_worker_process_count_vec",
Help: "The number of the working worker",
},
[]string{"type"},
)
metrics.WPTaskProcessDurationVec = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: cfg.MetricsNamespace,
Subsystem: cfg.MetricsSubsystem,
Name: "wp_task_process_duration_ms_by_name",
Help: "The duration histogram of worker pool task process in ms by name",
Buckets: []float64{0.1, 5, 10, 50, 100, 500, 1000},
},
[]string{"type", "name"},
)
metrics.Registry.MustRegister(metrics.WPTaskQueueBufferLenVec)
metrics.Registry.MustRegister(metrics.WPAddTaskWaitCountVec)
metrics.Registry.MustRegister(metrics.WPWorkerProcessCountVec)
metrics.Registry.MustRegister(metrics.WPTaskProcessDurationVec)
} // Метрики WorkerPool
return &metrics, nil
}
func (mt *Metrics) PrintMetricsToLog() {
metricFamilies, err := mt.Registry.Gather()
if err != nil {
_ = _err.WithCauseTyped(_err.ERR_COMMON_ERROR, _err.ERR_UNDEFINED_ID, err, err.Error()).PrintfError()
}
for _, metric := range metricFamilies {
_log.Info("Metrics: ", "\n"+proto.MarshalTextString(metric))
}
}
// Глобальные метрики
var gMetrics *Metrics
// Конфиг глобальных метрик по умолчанию
var gDefConfig = &Config{
MetricsNamespace: "com",
MetricsSubsystem: "app",
CollectDBCountVec: false,
CollectDBDurationVec: false,
CollectHTTPRequestsCountVec: false,
CollectHTTPErrorRequestsCountVec: false,
CollectHTTPRequestsDurationVec: false,
CollectHTTPActiveRequestsCount: false,
CollectHTTPRequestsDuration: false,
CollectHTTPClientCallCountVec: false,
CollectHTTPClientCallDurationVec: false,
CollectCalcCountVec: false,
CollectCalcDurationVec: false,
CollectMarshalingDurationVec: false,
CollectUnMarshalingDurationVec: false,
CollectWPTaskQueueBufferLenVec: false,
CollectWPAddTaskWaitCountVec: false,
CollectWPWorkerProcessCountVec: false,
CollectWPTaskProcessDurationVec: false,
}
func init() {
InitGlobalMetrics(gDefConfig)
}
func GlobalMetrics() *Metrics {
return gMetrics
}
// Метрики DB
func IncDBCountVec(sql string) {
if gMetrics.Cfg.CollectDBCountVec {
gMetrics.DBCountVec.WithLabelValues(sql).Inc()
}
}
func AddDBDurationVec(sql string, duration time.Duration) {
if gMetrics.Cfg.CollectDBDurationVec {
gMetrics.DBDurationVec.WithLabelValues(sql).Observe(float64(duration.Milliseconds()))
}
}
// Метрики HTTP
func IncHTTPRequestsCountVec(resource string, method string) {
if gMetrics.Cfg.CollectHTTPRequestsCountVec {
gMetrics.HTTPRequestsCountVec.WithLabelValues(resource, method).Inc()
}
}
func IncHTTPErrorRequestsCountVec(resource string, method string) {
if gMetrics.Cfg.CollectHTTPErrorRequestsCountVec {
gMetrics.HTTPErrorRequestsCountVec.WithLabelValues(resource, method).Inc()
}
}
func IncHTTPRequestsDurationVec(resource string, method string, state string, duration time.Duration) {
if gMetrics.Cfg.CollectHTTPRequestsDurationVec {
gMetrics.HTTPRequestsDurationVec.WithLabelValues(resource, method+": "+state).Observe(float64(duration.Milliseconds()))
}
}
func IncHTTPActiveRequestsCount() {
if gMetrics.Cfg.CollectHTTPActiveRequestsCount {
gMetrics.HTTPActiveRequestsCount.Inc()
}
}
func DecHTTPActiveRequestsCount() {
if gMetrics.Cfg.CollectHTTPActiveRequestsCount {
gMetrics.HTTPActiveRequestsCount.Dec()
}
}
func AddHTTPRequestsDuration(duration time.Duration) {
if gMetrics.Cfg.CollectHTTPRequestsDuration {
gMetrics.HTTPRequestsDuration.Observe(float64(duration.Milliseconds()))
}
}
// Метрики HTTP client call
func IncHTTPClientCallCountVec(resource string, method string) {
if gMetrics.Cfg.CollectHTTPClientCallCountVec {
gMetrics.HTTPClientCallCountVec.WithLabelValues(resource, method).Inc()
}
}
func IncHTTPClientCallDurationVec(resource string, method string, duration time.Duration) {
if gMetrics.Cfg.CollectHTTPClientCallDurationVec {
gMetrics.HTTPClientCallDurationVec.WithLabelValues(resource, method).Observe(float64(duration.Milliseconds()))
}
}
// Метрики вычислений
func IncCalcCountVec(label string) {
if gMetrics.Cfg.CollectCalcCountVec {
gMetrics.CalcCountVec.WithLabelValues(label).Inc()
}
}
func IncCalcDurationVec(label string, duration time.Duration) {
if gMetrics.Cfg.CollectCalcDurationVec {
gMetrics.CalcDurationVec.WithLabelValues(label).Observe(float64(duration.Milliseconds()))
}
}
// Метрики JSON
func IncMarshalingDurationVec(label string, duration time.Duration) {
if gMetrics.Cfg.CollectMarshalingDurationVec {
gMetrics.MarshalingDurationVec.WithLabelValues(label).Observe(float64(duration.Milliseconds()))
}
}
func IncUnMarshalingDurationVec(label string, duration time.Duration) {
if gMetrics.Cfg.CollectUnMarshalingDurationVec {
gMetrics.UnMarshalingDurationVec.WithLabelValues(label).Observe(float64(duration.Milliseconds()))
}
}
// Метрики WorkerPoolVec
func IncWPTaskQueueBufferLenVec(wpType string) {
if gMetrics.Cfg.CollectWPTaskQueueBufferLenVec {
gMetrics.WPTaskQueueBufferLenVec.WithLabelValues(wpType).Inc()
}
}
func DecWPTaskQueueBufferLenVec(wpType string) {
if gMetrics.Cfg.CollectWPTaskQueueBufferLenVec {
gMetrics.WPTaskQueueBufferLenVec.WithLabelValues(wpType).Dec()
}
}
func SetWPTaskQueueBufferLenVec(wpType string, len float64) {
if gMetrics.Cfg.CollectWPTaskQueueBufferLenVec {
gMetrics.WPTaskQueueBufferLenVec.WithLabelValues(wpType).Set(len)
}
}
func IncWPAddTaskWaitCountVec(wpType string) {
if gMetrics.Cfg.CollectWPAddTaskWaitCountVec {
gMetrics.WPAddTaskWaitCountVec.WithLabelValues(wpType).Inc()
}
}
func DecWPAddTaskWaitCountVec(wpType string) {
if gMetrics.Cfg.CollectWPAddTaskWaitCountVec {
gMetrics.WPAddTaskWaitCountVec.WithLabelValues(wpType).Dec()
}
}
func IncWPWorkerProcessCountVec(wpType string) {
if gMetrics.Cfg.CollectWPWorkerProcessCountVec {
gMetrics.WPWorkerProcessCountVec.WithLabelValues(wpType).Inc()
}
}
func DecWPWorkerProcessCountVec(wpType string) {
if gMetrics.Cfg.CollectWPWorkerProcessCountVec {
gMetrics.WPWorkerProcessCountVec.WithLabelValues(wpType).Dec()
}
}
func IncWPTaskProcessDurationVec(wpType string, name string, duration time.Duration) {
if gMetrics.Cfg.CollectWPTaskProcessDurationVec {
gMetrics.WPTaskProcessDurationVec.WithLabelValues(wpType, name).Observe(float64(duration.Milliseconds()))
}
}
func PrintGlobalMetricsToLog() {
gMetrics.PrintMetricsToLog()
}
func InitGlobalMetrics(cfg *Config) {
gMetrics, _ = New(cfg)
}