diff --git a/doc/dev/how-to/add_logging.md b/doc/dev/how-to/add_logging.md index b953dc081b3..a97f8b08053 100644 --- a/doc/dev/how-to/add_logging.md +++ b/doc/dev/how-to/add_logging.md @@ -107,8 +107,8 @@ func (w *Worker) DoSomething(params ...int) { If you are kicking off a long-running process, you can spawn a child logger and use it directly to maintain relevant context: ```go -func (w *Worker) DoBigThing(params ...int) { - doLog := w.logger.WithTrace(/* ... */).With("params", params) +func (w *Worker) DoBigThing(ctx context.Context, params ...int) { + doLog := trace.Logger(ctx, w.logger).With("params", params) // subsequent entries will have trace and params attached doLog.Info("starting the big thing") diff --git a/internal/trace/traceutil.go b/internal/trace/traceutil.go index d378f798979..b8035cda0f2 100644 --- a/internal/trace/traceutil.go +++ b/internal/trace/traceutil.go @@ -19,6 +19,7 @@ import ( "github.com/sourcegraph/sourcegraph/internal/trace/ot" "github.com/sourcegraph/sourcegraph/internal/tracer" "github.com/sourcegraph/sourcegraph/lib/errors" + sglog "github.com/sourcegraph/sourcegraph/lib/log" "github.com/sourcegraph/sourcegraph/lib/log/otfields" ) @@ -73,6 +74,15 @@ func ContextFromSpan(span opentracing.Span) *otfields.TraceContext { return nil } +// Logger will set the TraceContext on l if ctx has one. This is a +// convenience function around l.WithTrace for the common case. +func Logger(ctx context.Context, l sglog.Logger) sglog.Logger { + if tc := Context(ctx); tc != nil { + return l.WithTrace(*tc) + } + return l +} + // URL returns a trace URL for the given trace ID at the given external URL. func URL(traceID, externalURL, traceProvider string) string { if traceID == "" {