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.
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")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?