httprouter icon indicating copy to clipboard operation
httprouter copied to clipboard

how to log response status code

Open mikepc opened this issue 6 years ago • 1 comments

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)
		}()

	}
}

mikepc avatar Jun 10 '19 04:06 mikepc

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
        }
    }
}

loveuer avatar Jan 15 '20 08:01 loveuer