"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can you implement MDC logging in GoLang?

How can you implement MDC logging in GoLang?

Published on 2024-12-23
Browse:164

How can you implement MDC logging in GoLang?

MDC Logging in GoLang

Java's MDC Logging relies on thread local storage, which is not available in GoLang. However, a similar functionality can be achieved by threading a Context through the stack.

Java MDC relies on thread local storage, something Go does not have. The closest thing is to thread a Context through your stack, which is becoming a common practice in Go libraries.

One way to implement this is through a middleware package that adds a request ID to the context of a web request. This ID can then be retrieved and used throughout the stack for logging purposes.

Here's a simple example of a middleware package:

req = req.WithContext(context.WithValue(req.Context(), "requestId", ID))

The request ID can then be retrieved using:

ctx.Value("requestId")

This value can be used in a custom logger function:

func logStuff(ctx context.Context, msg string) {
    log.Println(ctx.Value("requestId"), msg) // call stdlib logger
}

This approach allows for easy tracing of concurrent requests by adding unique IDs to all server logs. There are other possible implementations, but this one provides a straightforward way to achieve MDC-like logging in GoLang.

Latest tutorial More>

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