-
Notifications
You must be signed in to change notification settings - Fork 2
/
metrics.go
96 lines (83 loc) · 2.47 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
package metrics
import (
"context"
"net/http"
"github.com/DataWorkbench/glog"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type Config struct {
Enabled bool `json:"enabled" yaml:"enabled" env:"ENABLED" validate:"-"`
// This is used for reporting the status of server directly through
// the HTTP address. Notice that there is a risk of leaking status
// information if this port is exposed to the public.
Address string `json:"address" yaml:"address" env:"ADDRESS" validate:"required_with=Enabled"`
// HTTP URI PATH
URLPath string `json:"url_path" yaml:"url_path" env:"URL_PATH,default=/metrics" validate:"required"`
}
// Server implements prometheus metrics server
type Server struct {
lp *glog.Logger
cfg *Config
h *http.Server
}
// NewServer return an new Server
// NOTICE: Must set glog.Logger into the ctx by glow.WithContext
func NewServer(ctx context.Context, cfg *Config) (*Server, error) {
if !cfg.Enabled {
return nil, nil
}
lp := glog.FromContext(ctx)
mux := http.NewServeMux()
// Expose the registered metrics via HTTP.
mux.Handle(cfg.URLPath, promhttp.HandlerFor(
prometheus.DefaultGatherer,
promhttp.HandlerOpts{
// Opt into OpenMetrics to support exemplars.
EnableOpenMetrics: true,
ErrorLog: &Logger{Output: lp},
},
))
s := &Server{
lp: lp,
cfg: cfg,
h: &http.Server{Addr: cfg.Address, Handler: mux},
}
return s, nil
}
func (s *Server) ListenAndServe() (err error) {
if s == nil {
return
}
s.lp.Info().String("prometheus metrics: server listening", s.cfg.Address+s.cfg.URLPath).Fire()
err = s.h.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
s.lp.Error().Error("prometheus metrics: listen and serve error", err).Fire()
return err
}
return
}
func (s *Server) Close() (err error) {
if s == nil {
return
}
s.lp.Info().Msg("prometheus metrics: waiting for server close").Fire()
if err = s.h.Close(); err != nil {
s.lp.Error().Error("prometheus metrics: server close error", err).Fire()
return
}
s.lp.Info().Msg("prometheus metrics: server closed").Fire()
return
}
func (s *Server) Shutdown(ctx context.Context) (err error) {
if s == nil {
return
}
s.lp.Info().Msg("prometheus metrics: waiting for server shutdown").Fire()
if err = s.h.Shutdown(ctx); err != nil {
s.lp.Error().Error("prometheus metrics: shutdown server error", err).Fire()
return
}
s.lp.Info().Msg("prometheus metrics: shutdown server done").Fire()
return
}