4 // LoggingResponseWriter
7 "github.com/gorilla/mux"
14 // LoggingResponseWriter has anonymous fields ResponseWriter and ResponseBody
15 type LoggingResponseWriter struct {
22 // WriteHeader writes header to ResponseWriter
23 func (loggingWriter *LoggingResponseWriter) WriteHeader(code int) {
24 loggingWriter.Status = code
25 loggingWriter.ResponseWriter.WriteHeader(code)
28 func (loggingWriter *LoggingResponseWriter) Write(data []byte) (int, error) {
29 loggingWriter.Length += len(data)
30 if loggingWriter.Status >= 400 {
31 loggingWriter.ResponseBody += string(data)
33 return loggingWriter.ResponseWriter.Write(data)
36 // LoggingRESTRouter is used to add logging capabilities to mux.Router
37 type LoggingRESTRouter struct {
41 // MakeLoggingRESTRouter initializes LoggingRESTRouter
42 func MakeLoggingRESTRouter() *LoggingRESTRouter {
43 router := MakeRESTRouter()
44 return (&LoggingRESTRouter{router})
47 func (loggingRouter *LoggingRESTRouter) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
49 loggingWriter := LoggingResponseWriter{http.StatusOK, 0, resp, ""}
50 loggingRouter.router.ServeHTTP(&loggingWriter, req)
51 statusText := http.StatusText(loggingWriter.Status)
52 if loggingWriter.Status >= 400 {
53 statusText = strings.Replace(loggingWriter.ResponseBody, "\n", "", -1)
55 log.Printf("[%s] %s %s %.6fs %d %d \"%s\"", req.RemoteAddr, req.Method, req.URL.Path[1:], time.Since(t0).Seconds(), loggingWriter.Status, loggingWriter.Length, statusText)