4 // LoggingResponseWriter
7 "github.com/gorilla/mux"
14 // LoggingResponseWriter has anonymous fields ResponseWriter and ResponseBody
15 type LoggingResponseWriter struct {
23 // WriteHeader writes header to ResponseWriter
24 func (loggingWriter *LoggingResponseWriter) WriteHeader(code int) {
25 if loggingWriter.sentHdr == zeroTime {
26 loggingWriter.sentHdr = time.Now()
28 loggingWriter.Status = code
29 loggingWriter.ResponseWriter.WriteHeader(code)
32 var zeroTime time.Time
34 func (loggingWriter *LoggingResponseWriter) Write(data []byte) (int, error) {
35 if loggingWriter.Length == 0 && len(data) > 0 && loggingWriter.sentHdr == zeroTime {
36 loggingWriter.sentHdr = time.Now()
38 loggingWriter.Length += len(data)
39 if loggingWriter.Status >= 400 {
40 loggingWriter.ResponseBody += string(data)
42 return loggingWriter.ResponseWriter.Write(data)
45 // LoggingRESTRouter is used to add logging capabilities to mux.Router
46 type LoggingRESTRouter struct {
50 // MakeLoggingRESTRouter initializes LoggingRESTRouter
51 func MakeLoggingRESTRouter() *LoggingRESTRouter {
52 router := MakeRESTRouter()
53 return (&LoggingRESTRouter{router})
56 func (loggingRouter *LoggingRESTRouter) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
58 loggingWriter := LoggingResponseWriter{http.StatusOK, 0, resp, "", zeroTime}
59 loggingRouter.router.ServeHTTP(&loggingWriter, req)
60 statusText := http.StatusText(loggingWriter.Status)
61 if loggingWriter.Status >= 400 {
62 statusText = strings.Replace(loggingWriter.ResponseBody, "\n", "", -1)
66 tLatency := loggingWriter.sentHdr.Sub(t0)
67 tResponse := now.Sub(loggingWriter.sentHdr)
68 log.Printf("[%s] %s %s %d %.6fs %.6fs %.6fs %d %d \"%s\"", req.RemoteAddr, req.Method, req.URL.Path[1:], req.ContentLength, tTotal.Seconds(), tLatency.Seconds(), tResponse.Seconds(), loggingWriter.Status, loggingWriter.Length, statusText)