How do I implement request logging and tracing?

In Go, implementing request logging and tracing can significantly aid in monitoring the health and performance of your applications. This entails capturing details about incoming requests, including timestamps, request paths, and any associated errors. Below is an example code snippet to demonstrate how to implement such logging.

package main import ( "log" "net/http" "time" ) // LoggingMiddleware is a middleware that logs incoming requests func LoggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() // Process the request next.ServeHTTP(w, r) // Log the request details log.Printf("Request: %s %s took %s", r.Method, r.URL.Path, time.Since(start)) }) } func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) }) // Wrap the mux with the logging middleware loggedMux := LoggingMiddleware(mux) // Start the server log.Println("Server starting on :8080") http.ListenAndServe(":8080", loggedMux) }

Go request logging tracing middleware web server performance monitoring