Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for trace.SpanContextFromContext so it is possible to get a tracer and span info to injected in logs #987

Open
hagen-p opened this issue Aug 7, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@hagen-p
Copy link

hagen-p commented Aug 7, 2024

I want to inject Trace information in my logs ,

To this I added the following code to my application, with this code I do not see the trace information printed as the SpanCtx is not valid.

I ideally I would like to call trace.SpanContextFromContext. to get the Span Context for the (global) Tracer

And use that to retrieve the current span/trace information

This might also be useful for adding span attributes

 package main

import (
	"github.com/sirupsen/logrus"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/trace"
)
func main() {
	ctx := context.TODO()
	ctx, span := otel.Tracer("github.com/my/repo").Start(ctx, "log info")
	defer span.End()
	spanCtx := trace.SpanContextFromContext(ctx)
	logrus.WithFields(LogrusFields(spanCtx)).Info("loaded users")
}

func LogrusFields(spanCtx trace.SpanContext) logrus.Fields {
	if !spanCtx.IsValid() {
		return logrus.Fields{}
	}
	return logrus.Fields{
		"span_id":     spanCtx.SpanID().String(),
		"trace_id":    spanCtx.TraceID().String(),
		"trace_flags": spanCtx.TraceFlags().String(),
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
2 participants