-
Notifications
You must be signed in to change notification settings - Fork 3
/
metrics.go
83 lines (67 loc) · 1.96 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
package metrics
import (
"context"
"github.com/alexfalkowski/go-service/env"
"github.com/alexfalkowski/go-service/errors"
"github.com/alexfalkowski/go-service/net"
"github.com/alexfalkowski/go-service/os"
"github.com/alexfalkowski/go-service/version"
otlp "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
"go.opentelemetry.io/otel/exporters/prometheus"
m "go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/metric/noop"
"go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
semconv "go.opentelemetry.io/otel/semconv/v1.25.0"
"go.uber.org/fx"
)
// NewNoopMeter for metrics.
func NewNoopMeter() m.Meter {
return noop.Meter{}
}
// MeterParams for metrics.
type MeterParams struct {
fx.In
Lifecycle fx.Lifecycle
Environment env.Environment
Version version.Version
Config *Config
Reader metric.Reader
}
// NewMeter for metrics.
func NewMeter(params MeterParams) m.Meter {
if !IsEnabled(params.Config) {
return NewNoopMeter()
}
name := os.ExecutableName()
attrs := resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName(name),
semconv.ServiceVersion(string(params.Version)),
semconv.DeploymentEnvironment(string(params.Environment)),
)
provider := metric.NewMeterProvider(metric.WithReader(params.Reader), metric.WithResource(attrs))
meter := provider.Meter(name)
params.Lifecycle.Append(fx.Hook{
OnStop: func(ctx context.Context) error {
err := provider.Shutdown(ctx)
if net.IsConnectionRefused(err) {
return nil
}
return errors.Prefix("stop metrics", err)
},
})
return meter
}
// NewReader for metrics.
func NewReader(cfg *Config) (metric.Reader, error) {
if !IsEnabled(cfg) {
return prometheus.New()
}
if cfg.IsOTLP() {
r, err := otlp.New(context.Background(), otlp.WithEndpointURL(cfg.Host))
return metric.NewPeriodicReader(r), errors.Prefix("new otlp", err)
}
e, err := prometheus.New()
return e, errors.Prefix("new prometheus", err)
}