-
Notifications
You must be signed in to change notification settings - Fork 2
/
prometheus.go
90 lines (74 loc) · 2.03 KB
/
prometheus.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
package metrics
import (
"context"
"fmt"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/zondax/golem/pkg/logger"
"net/http"
"sync"
"time"
)
// StartMetricsServer starts a prometheus server.
// Data Url is at localhost:<port>/metrics/<path>
// Normally you would use /metrics as endpoint and 9090 as port
type TaskMetrics interface {
Start() error
RegisterMetric(name string, help string, labels []string, handler MetricHandler) error
UpdateMetric(name string, value float64, labels ...string) error
IncrementMetric(name string, labels ...string) error
DecrementMetric(name string, labels ...string) error
Name() string
AppName() string
Stop() error
}
type MetricDetail struct {
Collector prometheus.Collector
Handler MetricHandler
}
type taskMetrics struct {
path string
port string
metrics map[string]MetricDetail
mux sync.RWMutex
appName string
}
func NewTaskMetrics(path, port, appName string) TaskMetrics {
if appName == "" {
panic("appName is mandatory")
}
return &taskMetrics{
path: path,
port: port,
appName: appName,
metrics: make(map[string]MetricDetail),
}
}
func (t *taskMetrics) Name() string {
return "metrics"
}
func (t *taskMetrics) AppName() string {
return t.appName
}
func (t *taskMetrics) Start() error {
router := chi.NewRouter()
logger.GetLoggerFromContext(context.Background()).Infof("Metrics (prometheus) starting: %v", t.port)
// Prometheus path
router.Get(t.path, promhttp.Handler().(http.HandlerFunc))
server := &http.Server{
Addr: fmt.Sprintf(":%s", t.port),
Handler: router,
ReadHeaderTimeout: 5 * time.Second,
}
err := server.ListenAndServe()
if err != nil {
logger.GetLoggerFromContext(context.Background()).Errorf("Prometheus server error: %v", err)
} else {
logger.GetLoggerFromContext(context.Background()).Errorf("Prometheus server serving at port %s", t.port)
}
return err
}
func (t *taskMetrics) Stop() error {
return nil
}