/
middleware.go
88 lines (69 loc) · 1.97 KB
/
middleware.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
package cron
import (
"context"
"fmt"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
const instrumName = "github.com/gowool/cron"
func MetricsMiddleware() (MiddlewareFunc, error) {
meter := otel.GetMeterProvider().Meter(instrumName)
taskTime, err := meter.Float64Histogram(
"cron.task.run_time",
metric.WithDescription("The time it took to execute the task."),
metric.WithUnit("ms"),
)
if err != nil {
return nil, err
}
return func(next TaskFunc) TaskFunc {
return func(ctx context.Context, job Job) error {
start := time.Now()
err := next(ctx, job)
dur := time.Since(start)
attrs := make([]attribute.KeyValue, 0, 3)
attrs = append(attrs, attribute.String("job_name", job.Name))
attrs = append(attrs, attribute.String("job_type", job.Type.String()))
attrs = append(attrs, statusAttr(err))
taskTime.Record(ctx, milliseconds(dur), metric.WithAttributes(attrs...))
return err
}
}, nil
}
func TracingMiddleware() MiddlewareFunc {
tracer := otel.GetTracerProvider().Tracer(instrumName)
return func(next TaskFunc) TaskFunc {
return func(ctx context.Context, job Job) error {
ctx, span := tracer.Start(ctx, fmt.Sprintf("execute.Job(%s)", job.Type),
trace.WithSpanKind(trace.SpanKindInternal),
trace.WithAttributes(
attribute.String("job_name", job.Name),
attribute.String("job_type", job.Type.String()),
),
)
defer span.End()
err := next(ctx, job)
recordError(span, err)
return err
}
}
}
func milliseconds(d time.Duration) float64 {
return float64(d) / float64(time.Millisecond)
}
func statusAttr(err error) attribute.KeyValue {
if err != nil {
return attribute.String("status", "error")
}
return attribute.String("status", "ok")
}
func recordError(span trace.Span, err error) {
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
}