forked from mtusi2026/mtusi2026lab6
feat: add OpenTelemetry instrumentation
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func TestConfigValidation(t *testing.T) {
|
||||
valid := Config{ServiceName: "messenger-api", InstanceID: "api-1", Environment: "lab", Namespace: "mtusi-highload"}
|
||||
require.NoError(t, valid.validate())
|
||||
|
||||
invalid := valid
|
||||
invalid.ServiceName = ""
|
||||
require.EqualError(t, invalid.validate(), "telemetry service name is required")
|
||||
}
|
||||
|
||||
func TestCorrelationHandlerAddsTraceAndRedactsSecrets(t *testing.T) {
|
||||
traceID, err := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
|
||||
require.NoError(t, err)
|
||||
spanID, err := trace.SpanIDFromHex("00f067aa0ba902b7")
|
||||
require.NoError(t, err)
|
||||
ctx := trace.ContextWithSpanContext(context.Background(), trace.NewSpanContext(trace.SpanContextConfig{
|
||||
TraceID: traceID, SpanID: spanID, TraceFlags: trace.FlagsSampled,
|
||||
}))
|
||||
first := &recordHandler{}
|
||||
second := &recordHandler{}
|
||||
handler := newCorrelationHandler(first, second)
|
||||
record := slog.NewRecord(time.Now(), slog.LevelInfo, "request", 0)
|
||||
record.AddAttrs(slog.String("event", "http_request_completed"), slog.String("authorization", "secret"))
|
||||
|
||||
require.NoError(t, handler.Handle(ctx, record))
|
||||
for _, captured := range []*recordHandler{first, second} {
|
||||
require.Equal(t, traceID.String(), captured.attributes["trace_id"])
|
||||
require.Equal(t, spanID.String(), captured.attributes["span_id"])
|
||||
require.Equal(t, "http_request_completed", captured.attributes["event"])
|
||||
require.NotContains(t, captured.attributes, "authorization")
|
||||
}
|
||||
}
|
||||
|
||||
type recordHandler struct {
|
||||
attributes map[string]string
|
||||
}
|
||||
|
||||
func (*recordHandler) Enabled(context.Context, slog.Level) bool { return true }
|
||||
func (h *recordHandler) Handle(_ context.Context, record slog.Record) error {
|
||||
h.attributes = make(map[string]string)
|
||||
record.Attrs(func(attribute slog.Attr) bool {
|
||||
h.attributes[attribute.Key] = attribute.Value.String()
|
||||
return true
|
||||
})
|
||||
return nil
|
||||
}
|
||||
func (h *recordHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
|
||||
func (h *recordHandler) WithGroup(string) slog.Handler { return h }
|
||||
Reference in New Issue
Block a user