I am building a web server in Golang. You know Golang has an context
package and it's offically recommended to always pass a context as first argument. context.Context
has a Value
method to keep variables under a context.
However, most logging libraries also privide a way to inherit logger, say, creating child loggers with fields from its parent. In logrus (or some other logger, doesn't matter), you may create an logrus.Entry
and apply WithFields
to get a child logger.
For example, when each HTTP request coming an request-id
is attached. I hope it being put in context, and also logged as a field in every log.
So, how to do this in a proper way?
THANKS!!
You can get the request-id
from the incoming request and then use the context to pass the request-id
to the functions you are calling. Here is an example of that : https://medium.com/@cep21/how-to-correctly-use-context-context-in-go-1-7-8f2c0fafdf39. For logging: Define your own logger using the std log library
func CreateCustomLogger(requestId string) *log.Logger {
defaultLoggingFlags :=
log.Ldate|log.Ltime|log.LUTC|log.Lmicroseconds|log.Lshortfile
return log.New(os.Stderr, requestId + ": ", defaultLoggingFlags)
}
In your function:
customLogger := CreateCustomLogger(requestId)
customLogger.Printf("Custom log message")