How do I integrate logging with context using logrus in Go?

Integrating logging with context in Go using the Logrus logging library is crucial for maintaining clean, informative logs, especially in applications with concurrent operations. Context allows you to pass request-scoped values, deadlines, and cancellation signals across API boundaries. This integration helps in tracing logs effectively.

Example: Integrating Logrus with Context

package main

import (
    "context"
    "fmt"
    "github.com/sirupsen/logrus"
    "net/http"
)

func main() {
    log := logrus.New()

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // Create a context with a value
        ctx := context.WithValue(r.Context(), "requestID", "12345")
        logRequest(ctx, log)
        fmt.Fprintln(w, "Hello, world!")
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

func logRequest(ctx context.Context, log *logrus.Logger) {
    // Retrieve value from context
    if requestID, ok := ctx.Value("requestID").(string); ok {
        log.WithFields(logrus.Fields{
            "requestID": requestID,
        }).Info("New request received")
    }
}

Go logging context Logrus log management request ID HTTP server