-
Notifications
You must be signed in to change notification settings - Fork 1
/
metrics.go
40 lines (35 loc) · 874 Bytes
/
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
package metrics
import (
"context"
"errors"
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/fx"
"go.uber.org/zap"
)
var Module = fx.Module(
"metrics",
fx.Provide(NewServer),
fx.Invoke(HookMetricsHandler),
)
func NewServer(c Config) *http.Server {
http.Handle("/metrics", promhttp.Handler())
return &http.Server{Addr: c.Addr}
}
func HookMetricsHandler(lifecycle fx.Lifecycle, server *http.Server, logger *zap.Logger) {
lifecycle.Append(fx.Hook{
OnStart: func(context.Context) error {
go func() {
err := server.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Fatal("failed to start metrics server", zap.Error(err))
}
}()
logger.Info("metrics server started")
return nil
},
OnStop: func(ctx context.Context) error {
return server.Shutdown(ctx)
},
})
}