Is there a static way to get the current request / context in Go?

I want my logging methods to return some kind of request id. To do this, I need to pass the request object (or some derivative) to the logging function.

It's okay when you register from request handlers, but it's problematic when using from library style methods as I don't want them to be aware of any current http requests.
In addition, the same library methods can be used in the future by console applications, and the request ID will be replaced with some kind of workflow ID.

Using context solves the problem, but it means I'll have to add a context parameter to all of my methods, which is somewhat annoying.

So, basically, I need some kind of static storage that is passed between method calls and goroutine.

I'm not sure if there is something like this in Go, so maybe my approach does not work entirely, in which case I would be glad to hear what is better for solving the above problem.

Thank,

+3


source to share


1 answer


Try using a different logging library. For example, in log15 ( https://github.com/inconshreveable/log15 ) Logger as inline key / value context.

logger := log.New("request_id", "8379870928")

      

You can pass the registrar object to anyone who needs to register. Later:



logger.Warn("blabalbla")

      

... will insert the request_id you put in.

0


source







All Articles