julienschmidt / httprouter

A high performance HTTP request router that scales well
https://pkg.go.dev/github.com/julienschmidt/httprouter
BSD 3-Clause "New" or "Revised" License
16.64k stars 1.47k forks source link

how to log response status code #273

Open mikepc opened 5 years ago

mikepc commented 5 years ago

For some reason the request's response object is nil, even when using defer.

How do I log the status code the endpoint resulted with?

func LogHandler(h httprouter.Handle) httprouter.Handle {
    return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

        lc := ToContext(r.Context(), SetupLogrus())

        requestID := r.Header.Get(REQUEST_ID)

        if requestID == "" {
            requestID = string(composeRequestID())
            r.Header.Set(REQUEST_ID, string(requestID))
        }
        f := setupRequestFields(r.Context(), w, r)
        delete(f, "status")

        AddFields(lc, f)
        req := r.WithContext(lc)
        h(w, req, ps)
        defer func() {
            l := Extract(lc)
            l.WithField("status", req.Response.StatusCode).Infof("%s %s", string(r.Method), r.URL)
        }()

    }
}
loveuer commented 4 years ago
func logger() midfunc {
    return func(next httprouter.Handle) httprouter.Handle {
        return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
            start := time.Now()

            // Initialize the status to 200 in case WriteHeader is not called
            sw := statusRecorder{w, 200}
            next(&sw, r, ps)
            log.Printf("[%s: %s :%d] [time: %v]\n", r.Method, r.URL.String(), sw.status, time.Since(start))
            return
        }
    }
}