-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.go
More file actions
43 lines (34 loc) · 1.13 KB
/
logging.go
File metadata and controls
43 lines (34 loc) · 1.13 KB
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
38
39
40
41
42
43
package main
import (
"net/http"
"time"
)
// loggingRoundTripper wraps an http.RoundTripper and logs HTTP requests/responses in verbose mode.
type loggingRoundTripper struct {
base http.RoundTripper
verbose bool
}
// newLoggingRoundTripper creates a new logging round tripper.
func newLoggingRoundTripper(base http.RoundTripper, verbose bool) http.RoundTripper {
if base == nil {
return &loggingRoundTripper{base: http.DefaultTransport, verbose: verbose}
}
return &loggingRoundTripper{base: base, verbose: verbose}
}
// RoundTrip executes a single HTTP transaction and logs the request/response.
func (l *loggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
ctx := req.Context()
if l.verbose {
LogDebugHTTP(ctx, "%s %s", req.Method, req.URL)
start := time.Now()
resp, err := l.base.RoundTrip(req)
elapsed := time.Since(start)
if err != nil {
LogDebugHTTP(ctx, "%s %s failed: %v (took %v)", req.Method, req.URL, err, elapsed)
return nil, err
}
LogDebugHTTP(ctx, "%s %s -> %d (took %v)", req.Method, req.URL, resp.StatusCode, elapsed)
return resp, nil
}
return l.base.RoundTrip(req)
}