7329: Add generic tests for empty block handling.
[arvados.git] / services / keepstore / logging_router.go
1 package main
2
3 // LoggingRESTRouter
4 // LoggingResponseWriter
5
6 import (
7         "github.com/gorilla/mux"
8         "log"
9         "net/http"
10         "strings"
11         "time"
12 )
13
14 // LoggingResponseWriter has anonymous fields ResponseWriter and ResponseBody
15 type LoggingResponseWriter struct {
16         Status int
17         Length int
18         http.ResponseWriter
19         ResponseBody string
20 }
21
22 // WriteHeader writes header to ResponseWriter
23 func (loggingWriter *LoggingResponseWriter) WriteHeader(code int) {
24         loggingWriter.Status = code
25         loggingWriter.ResponseWriter.WriteHeader(code)
26 }
27
28 func (loggingWriter *LoggingResponseWriter) Write(data []byte) (int, error) {
29         loggingWriter.Length += len(data)
30         if loggingWriter.Status >= 400 {
31                 loggingWriter.ResponseBody += string(data)
32         }
33         return loggingWriter.ResponseWriter.Write(data)
34 }
35
36 // LoggingRESTRouter is used to add logging capabilities to mux.Router
37 type LoggingRESTRouter struct {
38         router *mux.Router
39 }
40
41 // MakeLoggingRESTRouter initializes LoggingRESTRouter
42 func MakeLoggingRESTRouter() *LoggingRESTRouter {
43         router := MakeRESTRouter()
44         return (&LoggingRESTRouter{router})
45 }
46
47 func (loggingRouter *LoggingRESTRouter) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
48         t0 := time.Now()
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)
54         }
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)
56
57 }