Files

144 lines
4.8 KiB
Go

package observability
import (
"context"
"encoding/json"
"errors"
"log/slog"
"os"
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/log"
"go.opentelemetry.io/otel/log/global"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
var Tracer = otel.Tracer(scope)
var meter = otel.Meter(scope)
var (
httpRequests = instrument(meter.Int64Counter("messenger_http_requests"))
httpLatency = instrument(meter.Float64Histogram("messenger_http_request_duration", metric.WithUnit("s"),
metric.WithExplicitBucketBoundaries(.001, .003, .005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10)))
jobs = instrument(meter.Int64Counter("messenger_jobs"))
jobLatency = instrument(meter.Float64Histogram("messenger_job_duration", metric.WithUnit("s"),
metric.WithExplicitBucketBoundaries(.01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 40, 60, 120)))
readyLatency = instrument(meter.Float64Histogram("messenger_attachment_time_to_ready", metric.WithUnit("s"),
metric.WithExplicitBucketBoundaries(.05, .1, .25, .5, 1, 2, 5, 10, 20, 40, 60, 120, 300)))
lastExportError atomic.Int64
)
func instrument[T any](value T, err error) T {
if err != nil {
panic(err) // All instrument names and descriptors are code constants.
}
return value
}
func reportExportError() {
now := time.Now().Unix()
last := lastExportError.Load()
if last != now && lastExportError.CompareAndSwap(last, now) {
slog.Warn("OpenTelemetry export failed")
}
}
func ObserveHTTP(ctx context.Context, method, route string, code int, duration time.Duration) {
attrs := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route),
attribute.String("status_class", strconv.Itoa(code/100)+"xx"))
httpRequests.Add(ctx, 1, attrs)
httpLatency.Record(ctx, duration.Seconds(), attrs)
}
func ObserveJob(ctx context.Context, outcome string, duration time.Duration) {
attrs := metric.WithAttributes(attribute.String("job_type", "attachment.process"), attribute.String("outcome", outcome))
jobs.Add(ctx, 1, attrs)
jobLatency.Record(ctx, duration.Seconds(), attrs)
}
func ObserveReady(ctx context.Context, acceptedAt time.Time) {
readyLatency.Record(ctx, max(time.Since(acceptedAt).Seconds(), 0),
metric.WithAttributes(attribute.String("job_type", "attachment.process")))
}
// Log exports only deliberate operational fields, never arbitrary slog values.
// The JSON body allows LogQL queries and Grafana's trace link to use the same IDs.
func Log(ctx context.Context, event string, level log.Severity, fields ...attribute.KeyValue) {
values := make(map[string]any, len(fields)+3)
values["event"] = event
for _, field := range fields {
values[string(field.Key)] = field.Value.AsInterface()
}
if span := trace.SpanContextFromContext(ctx); span.IsValid() {
values["trace_id"], values["span_id"] = span.TraceID().String(), span.SpanID().String()
}
if requestID := RequestID(ctx); requestID != "" {
values["request_id"] = requestID
}
body, err := json.Marshal(values)
if err != nil {
return
}
var record log.Record
record.SetTimestamp(time.Now())
record.SetSeverity(level)
record.SetSeverityText(level.String())
record.SetBody(log.StringValue(string(body)))
global.GetLoggerProvider().Logger(scope).Emit(ctx, record)
}
type requestIDKey struct{}
func WithRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, requestIDKey{}, id)
}
func RequestID(ctx context.Context) string {
id, _ := ctx.Value(requestIDKey{}).(string)
return id
}
func End(span trace.Span, err error) {
if err != nil {
kind := "operation_failed"
switch {
case errors.Is(err, context.DeadlineExceeded):
kind = "deadline_exceeded"
case errors.Is(err, context.Canceled):
kind = "canceled"
}
span.SetAttributes(attribute.String("error.type", kind))
span.SetStatus(codes.Error, kind)
}
span.End()
}
func observeProcess(m metric.Meter) {
cpu := instrument(m.Float64ObservableCounter("messenger_process_cpu_time", metric.WithUnit("s")))
rss := instrument(m.Int64ObservableGauge("messenger_process_memory", metric.WithUnit("By")))
_, _ = m.RegisterCallback(func(_ context.Context, observer metric.Observer) error {
var usage syscall.Rusage
if err := syscall.Getrusage(syscall.RUSAGE_SELF, &usage); err == nil {
seconds := float64(usage.Utime.Sec+usage.Stime.Sec) + float64(usage.Utime.Usec+usage.Stime.Usec)/1e6
observer.ObserveFloat64(cpu, seconds)
}
// The production binaries run on Linux. statm reports resident pages.
if raw, err := os.ReadFile("/proc/self/statm"); err == nil {
if fields := strings.Fields(string(raw)); len(fields) > 1 {
if pages, err := strconv.ParseInt(fields[1], 10, 64); err == nil {
observer.ObserveInt64(rss, pages*int64(os.Getpagesize()))
}
}
}
return nil
}, cpu, rss)
}