Mdctx
Mapped Diagnostic Context for logging in golang
Install / Use
/learn @jcchavezs/MdctxREADME
mdctx
Mapped Diagnostic Context (MDC) for Go logging
The idea of Mapped Diagnostic Context is to provide a way to enrich log messages with pieces of information that could be not available in the scope where the logging actually occurs, but that can be indeed useful to better track the execution of the program.
Usage
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val := r.Header.Get(RequestIDHeader)
if val != "" {
ctx := mdctx.Add(r.Context(), "request_id", val)
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
func (r *repository) DoSomething(ctx context.Context, ...) {
logger := mdctx.With(ctx, r.logger)
...
logger.Log("key", "value")
}
Providers
Providers allows you to include additional context to the logs coming from other
sources. E.g. if a middleware include the request_id in the context under a private
key, you can use the API of that middleware to inject that request_id in the mdc.
package requestIDMiddleware
type reqIDKey string
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val := r.Header.Get(RequestIDHeader)
if val != "" {
r.WithContext(context.WithValue(r.Context(), reqIDKey, val))
}
next.ServeHTTP(w, r)
})
}
package requestID
func Provider(ctx context.Context) context.Context {
return context.WithValue(ctx, "request_id", ctx.Value(reqIDKey))
}
package main
func main() {
mdctx.RegisterProvider(requestID.Provider)
}
Related Skills
node-connect
341.6kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
xurl
341.6kA CLI tool for making authenticated requests to the X (Twitter) API. Use this skill when you need to post tweets, reply, quote, search, read posts, manage followers, send DMs, upload media, or interact with any X API v2 endpoint.
frontend-design
84.6kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
341.6kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
