-
Notifications
You must be signed in to change notification settings - Fork 6
/
logger.go
56 lines (43 loc) · 1.24 KB
/
logger.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package restli
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
"time"
)
// StandardLogger represents the standard Logger from the log package (log.std for those inclined to read the source
// code)
var StandardLogger stdLogger
type stdLogger struct{}
func (s stdLogger) Printf(format string, v ...interface{}) {
_ = log.Output(3, fmt.Sprintf(format, v...))
}
type logger interface {
Printf(format string, v ...interface{})
}
// LoggingRoundTripper is an http.RoundTripper that wraps a backing http.RoundTripper and logs all outbound queries
// (method, URL, headers and body) to the given logger
type LoggingRoundTripper struct {
http.RoundTripper
Logger logger
}
func (l *LoggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
reqBytes, err := httputil.DumpRequestOut(req, true)
if err != nil {
return nil, err
}
l.Logger.Printf("\n\n%s\n\n\nSubmitting request\n", string(reqBytes))
startTime := time.Now()
res, err := l.RoundTripper.RoundTrip(req)
if err != nil {
return res, err
}
flightTime := time.Since(startTime)
resBytes, err := httputil.DumpResponse(res, true)
if err != nil {
return nil, err
}
l.Logger.Printf("Received response in %v:\n\n%s\n\n", flightTime, string(resBytes))
return res, nil
}