-
Notifications
You must be signed in to change notification settings - Fork 0
/
logging.go
62 lines (54 loc) · 1.08 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"bytes"
"io"
"net/http"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type LoggingHTTPClient struct {
logBody bool
*http.Client
}
func (lhc *LoggingHTTPClient) Do(req *http.Request) (*http.Response, error) {
res, err := lhc.Client.Do(req)
if err != nil {
return nil, err
}
event := log.Debug().
Str("method", req.Method).
Str("url", req.URL.String()).
Int("status", res.StatusCode)
if lhc.logBody {
res.Body = newLoggingBody(event, res.Body)
} else {
event.Msg("LoggingHTTPClient")
}
return res, err
}
type loggingBody struct {
event *zerolog.Event
buf bytes.Buffer
io.ReadCloser
}
func (l *loggingBody) Read(p []byte) (int, error) {
n, err := l.ReadCloser.Read(p)
if n > 0 {
if n, _ := l.buf.Write(p[:n]); err != nil {
return n, err
}
}
return n, err
}
func (l *loggingBody) Close() error {
l.event.
Bytes("body", l.buf.Bytes()).
Msg("")
return l.ReadCloser.Close()
}
func newLoggingBody(event *zerolog.Event, inner io.ReadCloser) io.ReadCloser {
return &loggingBody{
event: event,
ReadCloser: inner,
}
}