forked from mtusi2026/mtusi2026lab7
75 lines
2.0 KiB
Go
75 lines
2.0 KiB
Go
package telemetry
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"strings"
|
|
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
type correlationHandler struct {
|
|
stdout slog.Handler
|
|
otel slog.Handler
|
|
}
|
|
|
|
func newCorrelationHandler(stdout, otel slog.Handler) slog.Handler {
|
|
return correlationHandler{stdout: stdout, otel: otel}
|
|
}
|
|
|
|
func (h correlationHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
|
return h.stdout.Enabled(ctx, level) || h.otel.Enabled(ctx, level)
|
|
}
|
|
|
|
func (h correlationHandler) Handle(ctx context.Context, record slog.Record) error {
|
|
span := trace.SpanContextFromContext(ctx)
|
|
if span.IsValid() {
|
|
record.AddAttrs(slog.String("trace_id", span.TraceID().String()), slog.String("span_id", span.SpanID().String()))
|
|
}
|
|
record = sanitizedRecord(record)
|
|
if err := h.stdout.Handle(ctx, record); err != nil {
|
|
return err
|
|
}
|
|
return h.otel.Handle(ctx, record)
|
|
}
|
|
|
|
func (h correlationHandler) WithAttrs(attributes []slog.Attr) slog.Handler {
|
|
attributes = sanitizedAttributes(attributes)
|
|
return correlationHandler{stdout: h.stdout.WithAttrs(attributes), otel: h.otel.WithAttrs(attributes)}
|
|
}
|
|
|
|
func (h correlationHandler) WithGroup(name string) slog.Handler {
|
|
return correlationHandler{stdout: h.stdout.WithGroup(name), otel: h.otel.WithGroup(name)}
|
|
}
|
|
|
|
func sanitizedRecord(record slog.Record) slog.Record {
|
|
copy := slog.NewRecord(record.Time, record.Level, record.Message, record.PC)
|
|
record.Attrs(func(attribute slog.Attr) bool {
|
|
if !sensitiveKey(attribute.Key) {
|
|
copy.AddAttrs(attribute)
|
|
}
|
|
return true
|
|
})
|
|
return copy
|
|
}
|
|
|
|
func sanitizedAttributes(attributes []slog.Attr) []slog.Attr {
|
|
result := make([]slog.Attr, 0, len(attributes))
|
|
for _, attribute := range attributes {
|
|
if !sensitiveKey(attribute.Key) {
|
|
result = append(result, attribute)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func sensitiveKey(key string) bool {
|
|
key = strings.ToLower(key)
|
|
for _, marker := range []string{"authorization", "password", "secret", "token", "cookie", "body", "payload"} {
|
|
if strings.Contains(key, marker) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|