4869: Keepstore now returns Content-Length headers, and logs the error message
[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         Response 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.Response += 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         if loggingWriter.Status >= 400 {
46                 log.Printf("[%s] %s %s %d %d '%s'", req.RemoteAddr, req.Method, req.URL.Path[1:], loggingWriter.Status, loggingWriter.Length, strings.TrimSpace(loggingWriter.Response))
47         } else {
48                 log.Printf("[%s] %s %s %d %d", req.RemoteAddr, req.Method, req.URL.Path[1:], loggingWriter.Status, loggingWriter.Length)
49         }
50 }