Golang http server logging middleware
- User
Golang http server logging middleware
- Assistant
Certainly! Below is a simple example of an HTTP server in Go with logging middleware that logs the request method, URL path, and the time it took to process the request.
package main import ( "log" "net/http" "time" ) // loggingMiddleware is middleware that logs the incoming HTTP requests. func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() // Process request next.ServeHTTP(w, r) // Log details after serving the request duration := time.Since(start) log.Printf("%s %s %s", r.Method, r.URL.Path, duration) }) } func helloHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, World!")) } func main() { mux := http.NewServeMux() mux.HandleFunc("/", helloHandler) // Wrap the mux with logging middleware loggedMux := loggingMiddleware(mux) log.Println("Server is running at :8080") if err := http.ListenAndServe(":8080", loggedMux); err != nil { log.Fatalf("Failed to start server: %v", err) } }How it works:
- The
loggingMiddlewarefunction takes anhttp.Handlerand returns a newhttp.Handlerthat wraps the original one. - Before the request is passed down (
next.ServeHTTP), it records the current time. - After the handler has served the request, it calculates the duration and logs the HTTP method, URL path, and how long it took.
- The server runs on port 8080 and responds with "Hello, World!" at the root path
/.
Running:
Save the code in a file
main.goand run:go run main.goWhen you visit
http://localhost:8080/in your browser or curl, you’ll see logs like:GET / 480.123µsLet me know if you want it to log request body, response status code, or other details!
- The
- User
What's some common stuff to log?
- Assistant
Great question! In an HTTP server, logging is essential for monitoring, debugging, and auditing. Here are some common fields and pieces of information you typically want to log for each incoming HTTP request:
Common Stuff to Log in HTTP Server Logs
Field Description Why it's useful Timestamp The date and time the request was received Helps correlate events and troubleshoot issues chronologically HTTP Method (GET, POST, etc.) Indicates the requested action Understand what actions users/clients are performing Request URI / Path Which resource was requested Identify endpoints being accessed Query Parameters Any query string data Useful to see filters, search queries, or parameters Status Code (e.g. 200, 404, 500) HTTP response status Know if requests succeeded or failed Response Size Number of bytes sent to client Track data volume and how heavy responses are Duration / Latency Time taken to process the request Detect slow endpoints or performance bottlenecks Client IP Address IP of the requester Security auditing, rate limiting, geo-analysis User Agent Client software (browsers, API clients, bots) Identify traffic sources and bot activity Referer Where the request originated from (if any) Useful for analytics and debugging referral links Request ID / Trace ID (if applicable) A unique ID for each request Facilitate correlating logs in distributed systems Errors / Stack traces (if occurred) Details of any failures Troubleshoot problems effectively Headers (some important ones like Authorization, Content-Type) Context about payload and auth Useful in debugging client requests Request Body (typically for POST/PUT) Payload sent by client Debug data integrity and API usage (log sparingly due to size/security)
Example of Enhanced Logging Middleware (adding status code, client IP, user agent):
package main import ( "log" "net/http" "time" ) // responseWriterWrapper wraps the standard http.ResponseWriter to capture status code and response size type responseWriterWrapper struct { http.ResponseWriter statusCode int responseSize int } func (rw *responseWriterWrapper) WriteHeader(status int) { rw.statusCode = status rw.ResponseWriter.WriteHeader(status) } func (rw *responseWriterWrapper) Write(b []byte) (int, error) { size, err := rw.ResponseWriter.Write(b) rw.responseSize += size return size, err } func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() rw := &responseWriterWrapper{ResponseWriter: w, statusCode: 200} // Call the next handler next.ServeHTTP(rw, r) duration := time.Since(start) clientIP := r.RemoteAddr userAgent := r.UserAgent() method := r.Method path := r.URL.RequestURI() status := rw.statusCode size := rw.responseSize log.Printf( "%s %s %d %dB %s ClientIP:%s UA:%s", method, path, status, size, duration, clientIP, userAgent, ) }) }
Summary
What you log depends on your use case and compliance/security policies (e.g., personally identifiable info, headers containing sensitive info like Authorization tokens should be handled carefully). For most web services, logging something like:
- Timestamp (often automatic in log systems)
- HTTP method & URL path (+ query string if applicable)
- Response status code
- Request duration
- Client IP address
- User agent
is a solid baseline.
If you want, I can help you build a more advanced logger with structured JSON output or integration with logging frameworks!