Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

Golang http server logging middleware

  1. User

    Golang http server logging middleware

  2. 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 loggingMiddleware function takes an http.Handler and returns a new http.Handler that 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.go and run:

    go run main.go
    

    When you visit http://localhost:8080/ in your browser or curl, you’ll see logs like:

    GET / 480.123µs
    

    Let me know if you want it to log request body, response status code, or other details!

  3. User

    What's some common stuff to log?

  4. 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

    FieldDescriptionWhy it's useful
    TimestampThe date and time the request was receivedHelps correlate events and troubleshoot issues chronologically
    HTTP Method (GET, POST, etc.)Indicates the requested actionUnderstand what actions users/clients are performing
    Request URI / PathWhich resource was requestedIdentify endpoints being accessed
    Query ParametersAny query string dataUseful to see filters, search queries, or parameters
    Status Code (e.g. 200, 404, 500)HTTP response statusKnow if requests succeeded or failed
    Response SizeNumber of bytes sent to clientTrack data volume and how heavy responses are
    Duration / LatencyTime taken to process the requestDetect slow endpoints or performance bottlenecks
    Client IP AddressIP of the requesterSecurity auditing, rate limiting, geo-analysis
    User AgentClient software (browsers, API clients, bots)Identify traffic sources and bot activity
    RefererWhere the request originated from (if any)Useful for analytics and debugging referral links
    Request ID / Trace ID (if applicable)A unique ID for each requestFacilitate correlating logs in distributed systems
    Errors / Stack traces (if occurred)Details of any failuresTroubleshoot problems effectively
    Headers (some important ones like Authorization, Content-Type)Context about payload and authUseful in debugging client requests
    Request Body (typically for POST/PUT)Payload sent by clientDebug 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!