Add request-id to different logs - best practice with context

I have a REST API written with gorilla/mux v1.7.3 in go1.13.
I’m the only one in the team “proficient” in Golang, so I really wanted someone to tell me what I’m about to do is fine, and is good/bad practice.

I have plenty of logs - requests, stdout, errors and dependencies (mongo, db, etc).
I want to stick the request-id to each one of them.

After some digging and researching - from what I understood the best practice is to do so with the context library.

So basically using a middleware to store the request-id in the context:

	id := uuid.New().String()
	ctx := goContext.WithValue(r.Context(), "request-id", id)
	r = r.WithContext(ctx)
	w.Header().Set("request-id", id)
	next.ServeHTTP(w, r)
	return

So in order to use this “request-id”, I really need to pass the context request- r.Context() to every function call?
This seems very hard to grasp.
So at the start of every request, declaring ctx := r.Context() and passing it around to all other methods.

From what I understood, this is good practice and I should do that. So following this step, now I need to extract the request-id from the context. So for example, a (very simplified) log would be:

func RequestInfo(ctx context.Context, msg string) {
	fmt.Println(fmt.Sprintf("%v", ctx.Value("request-id")), msg)
}

Is this fine? Basically I’ll be using ctx.Value(..) quite a lot. From what I see this shouldn’t cause performance issues since it doesn’t lock anything when extracting the value.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.