How to log messages with additional context information (e.g., request ID) in Go?

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:

  1. Create a custom logger struct that includes the necessary fields for additional context information:
type customLogger struct { logger *log.Logger requestID string }
  1. Create a new function to initialize and return a custom logger:
func NewCustomLogger(logger *log.Logger, requestID string) *customLogger { return &customLogger{ logger: logger, requestID: requestID, } }
  1. Add a new method to the custom logger to log messages with the request ID:
func (cl *customLogger) LogWithRequestID(message string) { cl.logger.Println(cl.requestID, message) }
  1. Use the custom logger in your application code:
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.