Trace ID in the slog Package
This article focuses on incorporating trace IDs into the slog package for Golang. The slog package facilitates JSON output, making it an ideal tool for tracing requests.
Adding Trace ID with Context Values
To add a trace ID, you can leverage Golang's context values:
import "context"
ctx := context.Background()
ctx = context.WithValue(ctx, "traceId", "myTraceId")
Creating a Customized Logger with Trace ID
Once you have the trace ID in the context, you can create a logger that includes it:
traceId = ctx.Value("traceId")
newLogger := logger.With("traceId", traceId)
Utilizing the New Logger with Trace ID
All messages logged using the newLogger will now include the trace ID:
newLogger.Info("message with trace ID")
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3