Home > Backend Development > Golang > How Can I Effectively Log Both HTTP Requests and Responses in Go?

How Can I Effectively Log Both HTTP Requests and Responses in Go?

Barbara Streisand
Release: 2024-12-05 21:57:12
Original
767 people have browsed it

How Can I Effectively Log Both HTTP Requests and Responses in Go?

Logging HTTP Responses Enhancements

Logging HTTP requests is a crucial aspect of debugging and performance monitoring. While there are solutions like Gorilla's LoggingHandler for logging requests, logging responses is often an overlooked task.

To address this, let's explore a modified version of Eric Broda's accepted answer that both logs responses and forwards them to the client:

func logHandler(fn http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        x, err := httputil.DumpRequest(r, true)
        if err != nil {
            http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
            return
        }
        log.Println(fmt.Sprintf("%q", x))
        rec := httptest.NewRecorder()
        fn(rec, r)
        log.Println(fmt.Sprintf("%q", rec.Body))

        // Forward the response to the client
        for k, v := range rec.HeaderMap {
            w.Header()[k] = v
        }
        w.WriteHeader(rec.Code)
        rec.Body.WriteTo(w)
    }
}
Copy after login

This modified function achieves the following:

  • Logs the request as before.
  • Creates a httptest.NewRecorder to capture the response.
  • Calls the original handler function, which writes the response to the recorder.
  • Logs the response from the recorder.
  • Copies the recorder's headers and status code to the actual response writer.
  • Forwards the recorder's body to the client.

By integrating this modified function into your application, you can seamlessly log both requests and responses, providing a comprehensive view of your HTTP communication.

The above is the detailed content of How Can I Effectively Log Both HTTP Requests and Responses in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template