In Go, you can log messages with additional context information, such as a request ID, by using the log
package and a custom logger that extends the log.Logger
struct. Here's an example of how you can accomplish this:
type customLogger struct {
logger *log.Logger
requestID string
}
func NewCustomLogger(logger *log.Logger, requestID string) *customLogger {
return &customLogger{
logger: logger,
requestID: requestID,
}
}
func (cl *customLogger) LogWithRequestID(message string) {
cl.logger.Println(cl.requestID, message)
}
func main() {
logger := log.New(os.Stdout, "", log.LstdFlags)
requestID := "1234"
customLogger := NewCustomLogger(logger, requestID)
customLogger.LogWithRequestID("This is an example log message")
}
With this approach, each log message output will include the request ID as additional context information.
Note: You can extend the custom logger struct with more fields, depending on the additional context information you want to include in your log messages.