Skip to content

Commit

Permalink
martian: add TraceID aware logger wrapper
Browse files Browse the repository at this point in the history
Move trace ID logging logic close to traceID.
Use logger stacking to add features to logs.

This is only temporary and traceID should be moved to the toplevel log package.
To make it work we would need to change the main Logger interface, see #544.
  • Loading branch information
mmatczuk committed Feb 9, 2024
1 parent 151dc0c commit 180dac0
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions internal/martian/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
package martian

import (
"context"
"fmt"
"sync/atomic"
"time"

"github.com/saucelabs/forwarder/internal/martian/log"
)

// traceID is a unique identifier for a request.
Expand All @@ -32,3 +35,28 @@ func (t traceID) String() string {
func (t traceID) Duration() time.Duration {
return time.Since(t.createdAt)
}

type TraceIDPrependingLogger struct {
log.Logger
}

func (l TraceIDPrependingLogger) Infof(ctx context.Context, format string, args ...any) {
l.Logger.Infof(ctx, l.format(ctx, format), args...)
}

func (l TraceIDPrependingLogger) Debugf(ctx context.Context, format string, args ...any) {
l.Logger.Debugf(ctx, l.format(ctx, format), args...)
}

func (l TraceIDPrependingLogger) Errorf(ctx context.Context, format string, args ...any) {
l.Logger.Errorf(ctx, l.format(ctx, format), args...)
}

var _ log.Logger = TraceIDPrependingLogger{}

func (l TraceIDPrependingLogger) format(ctx context.Context, format string) string {
if id := TraceID(ctx); id != "" {
return fmt.Sprintf("[%s] %s", id, format)
}
return format
}

0 comments on commit 180dac0

Please sign in to comment.