How do I log errors with context in Go?

In Go, logging errors effectively with context is essential for diagnosing issues in your applications. By including context, you can provide more meaningful error messages that help you trace back the source of the error.

To log errors with context, you can use the standard log package along with the context package. Here's a simple example:

package main import ( "context" "errors" "log" "time" ) func main() { ctx := context.Background() ctx = context.WithValue(ctx, "requestID", "12345") err := doSomething(ctx) if err != nil { logError(ctx, err) } } func doSomething(ctx context.Context) error { // Simulating an error return errors.New("an unexpected error occurred") } func logError(ctx context.Context, err error) { requestID := ctx.Value("requestID").(string) log.Printf("Request ID: %s, Error: %s", requestID, err) }

Go logging error handling in Go context in Go Go programming Go error logging