Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Logging with Mapped Diagnostic Context

Tags:

go

mdc

How can I achieve MDC Logging (Java) in GoLang?

I need to add UUIDs in all server logs in order to be able to trace concurrent requests.

like image 731
Gabe Avatar asked Dec 08 '16 21:12

Gabe


Video Answer


1 Answers

Java MDC relies on thread local storage, something Go does not have.

The closest thing is to thread a Context through your stack.

This is what more and more libraries are doing in Go.

A somewhat typical way is to do this via a middleware package that adds a request id to the context of a web request, like:

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

Then, assuming you pass the context around, you pull it out with ctx.Value("requestId") and use it wherever it makes sense.

Possibly making your own custom logger function like:

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

There's a bunch of ways you may want to handle this, but that's a fairly simple form.

like image 86
David Budworth Avatar answered Sep 25 '22 11:09

David Budworth