-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlog.go
More file actions
33 lines (28 loc) · 790 Bytes
/
log.go
File metadata and controls
33 lines (28 loc) · 790 Bytes
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
package mid
import (
"log"
"net/http"
)
// Log adds logging on entry to and exit from an [http.Handler] using [log.Printf].
//
// If the request is decorated with a trace ID
// (see [Trace]),
// it is included in the generated log lines.
func Log(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
traceID := TraceID(ctx)
if traceID != "" {
log.Printf("< %s %s [%s]", req.Method, req.URL, traceID)
} else {
log.Printf("< %s %s", req.Method, req.URL)
}
ww := ResponseWrapper{W: w}
next.ServeHTTP(&ww, req)
if traceID != "" {
log.Printf("> %d %s %s [%s]", ww.Result(), req.Method, req.URL, traceID)
} else {
log.Printf("> %d %s %s", ww.Result(), req.Method, req.URL)
}
})
}