github.com/sirupsen/logrus

github.com/sirupsen/logrus

Structured, pluggable logging for Go.

Inject DDContextLogHook

Join Point
Definition of logrus.Logger
Advice
Introduce new declarations:
// Using the following synthetic imports:
import (
	ext "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
	telemetry "gopkg.in/DataDog/dd-trace-go.v1/internal/telemetry"
	tracer "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)
func init() {
	telemetry.LoadIntegration("sirupsen/logrus")
	tracer.MarkIntegrationImported("github.com/sirupsen/logrus")
}

// DDContextLogHook ensures that any span in the log context is correlated to log output.
type DDContextLogHook struct{}

// Levels implements logrus.Hook interface, this hook applies to all defined levels
func (d *DDContextLogHook) Levels() []Level {
	return []Level{PanicLevel, FatalLevel, ErrorLevel, WarnLevel, InfoLevel, DebugLevel, TraceLevel}
}

// Fire implements logrus.Hook interface, attaches trace and span details found in entry context
func (d *DDContextLogHook) Fire(e *Entry) error {
	span, found := tracer.SpanFromContext(e.Context)
	if !found {
		return nil
	}
	e.Data[ext.LogKeyTraceID] = span.Context().TraceID()
	e.Data[ext.LogKeySpanID] = span.Context().SpanID()
	return nil
}

Trace logrus.New

Join Point
All of
Advice
Prepend statements produced by the following template:
{{- $logger := .Function.Result 0 -}}
defer func() {
	{{ $logger }}.AddHook(&DDContextLogHook{})
}()

Wrap logrus.Logger (pointer)

Join Point
Struct literal logrus.Logger
  • Pointer
Advice
Replace the expression using the template:
// Using the following synthetic imports:
import (
	logrus "github.com/sirupsen/logrus"
)
func(logger *logrus.Logger) *logrus.Logger {
	logger.AddHook(&logrus.DDContextLogHook{})
	return logger
}({{ . }})

Wrap logrus.Logger (value)

Join Point
Struct literal logrus.Logger
  • Value
Advice
Replace the expression using the template:
// Using the following synthetic imports:
import (
	logrus "github.com/sirupsen/logrus"
)
func(logger logrus.Logger) logrus.Logger {
	logger.AddHook(&logrus.DDContextLogHook{})
	return logger
}({{ . }})