-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlogger.go
53 lines (43 loc) · 1.41 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
// HTTP API Request Logger
package logger
// Load Dependencies
import (
"log"
"net/http"
"time"
)
type RoundLogged struct {
rt http.RoundTripper
log HTTPLogger
}
func (c *RoundLogged) RoundTrip(request *http.Request) (*http.Response, error) {
c.log.LogReq(request) // Log the Request
st := time.Now() // Start time
response, err := c.rt.RoundTrip(request)
duration := time.Since(st)
c.log.LogRes(request, response, err, duration)
return response, err
}
func NewLoggedTransport(rt http.RoundTripper, log HTTPLogger) http.RoundTripper {
return &RoundLogged{rt: rt, log: log}
}
// HTTPLogger defines the interface to log all http request and responses
type HTTPLogger interface {
LogReq(*http.Request)
LogRes(*http.Request, *http.Response, error, time.Duration)
}
type DefaultLogger struct {
}
//Log Requests
func (dl DefaultLogger) LogReq(*http.Request) {
}
// Log Response
func (dl DefaultLogger) LogRes(req *http.Request, res *http.Response, err error, duration time.Duration) {
duration /= time.Millisecond
if err != nil {
log.Printf("HTTP Request method=%s host=%s path=%s status=error durationMs=%d error=%q", req.Method, req.Host, req.URL.Path, duration, err.Error())
} else {
log.Printf("HTTP Request method=%s host=%s path=%s status=%d durationMs=%d", req.Method, req.Host, req.URL.Path, res.StatusCode, duration)
}
}
var DefaultLoggedTransport = NewLoggedTransport(http.DefaultTransport, DefaultLogger{})