Merge branch 'master' into 4523-search-index
[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 )
12
13 type LoggingResponseWriter struct {
14         Status int
15         Length int
16         http.ResponseWriter
17         ResponseBody string
18 }
19
20 func (loggingWriter *LoggingResponseWriter) WriteHeader(code int) {
21         loggingWriter.Status = code
22         loggingWriter.ResponseWriter.WriteHeader(code)
23 }
24
25 func (loggingWriter *LoggingResponseWriter) Write(data []byte) (int, error) {
26         loggingWriter.Length += len(data)
27         if loggingWriter.Status >= 400 {
28                 loggingWriter.ResponseBody += string(data)
29         }
30         return loggingWriter.ResponseWriter.Write(data)
31 }
32
33 type LoggingRESTRouter struct {
34         router *mux.Router
35 }
36
37 func MakeLoggingRESTRouter() *LoggingRESTRouter {
38         router := MakeRESTRouter()
39         return (&LoggingRESTRouter{router})
40 }
41
42 func (loggingRouter *LoggingRESTRouter) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
43         loggingWriter := LoggingResponseWriter{200, 0, resp, ""}
44         loggingRouter.router.ServeHTTP(&loggingWriter, req)
45         statusText := "OK"
46         if loggingWriter.Status >= 400 {
47                 statusText = strings.Replace(loggingWriter.ResponseBody, "\n", "", -1)
48         }
49         log.Printf("[%s] %s %s %d %d \"%s\"", req.RemoteAddr, req.Method, req.URL.Path[1:], loggingWriter.Status, loggingWriter.Length, statusText)
50
51 }