/
api_logging.go
89 lines (77 loc) · 1.74 KB
/
api_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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package api
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httputil"
log "github.com/akutz/gournal"
)
func isBinOctetBody(h http.Header) bool {
return h.Get(headerKeyContentType) == headerValContentTypeBinaryOctetStream
}
func logRequest(ctx context.Context, w io.Writer, req *http.Request) {
fmt.Fprintln(w, "")
fmt.Fprint(w, " -------------------------- ")
fmt.Fprint(w, "GOISILON HTTP REQUEST")
fmt.Fprintln(w, " -------------------------")
buf, err := httputil.DumpRequest(req, !isBinOctetBody(req.Header))
if err != nil {
return
}
WriteIndented(w, buf)
fmt.Fprintln(w)
}
func logResponse(ctx context.Context, res *http.Response) {
w := &bytes.Buffer{}
fmt.Fprintln(w)
fmt.Fprint(w, " -------------------------- ")
fmt.Fprint(w, "GOISILON HTTP RESPONSE")
fmt.Fprintln(w, " -------------------------")
buf, err := httputil.DumpResponse(res, !isBinOctetBody(res.Header))
if err != nil {
return
}
bw := &bytes.Buffer{}
WriteIndented(bw, buf)
scanner := bufio.NewScanner(bw)
for {
if !scanner.Scan() {
break
}
fmt.Fprintln(w, scanner.Text())
}
log.Debug(ctx, w.String())
}
// WriteIndentedN indents all lines n spaces.
func WriteIndentedN(w io.Writer, b []byte, n int) error {
s := bufio.NewScanner(bytes.NewReader(b))
if !s.Scan() {
return nil
}
l := s.Text()
for {
for x := 0; x < n; x++ {
if _, err := fmt.Fprint(w, " "); err != nil {
return err
}
}
if _, err := fmt.Fprint(w, l); err != nil {
return err
}
if !s.Scan() {
break
}
l = s.Text()
if _, err := fmt.Fprint(w, "\n"); err != nil {
return err
}
}
return nil
}
// WriteIndented indents all lines four spaces.
func WriteIndented(w io.Writer, b []byte) error {
return WriteIndentedN(w, b, 4)
}