-
Notifications
You must be signed in to change notification settings - Fork 0
/
logging.go
37 lines (30 loc) · 946 Bytes
/
logging.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package middleware
import (
"net/http"
"strings"
"time"
"github.com/go-chi/chi/middleware"
"github.com/pralolik/templgrid/src/logging"
)
func Logging(log logging.Logger) func(next http.Handler) http.Handler {
format := "%s %d %s Remote: %s %s"
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
start := time.Now().UTC()
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
status := ww.Status()
switch {
case strings.Contains(r.RequestURI, "/health"):
log.Info(format, r.Method, status, r.RequestURI, r.RemoteAddr, time.Since(start).String())
default:
if status >= 400 {
log.Error(format, r.Method, status, r.RequestURI, r.RemoteAddr, time.Since(start).String())
} else {
log.Info(format, r.Method, status, r.RequestURI, r.RemoteAddr, time.Since(start).String())
}
}
}
return http.HandlerFunc(fn)
}
}