|
1 | 1 | package middlewares |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
4 | 8 | "net/http" |
| 9 | + "net/url" |
| 10 | + "strings" |
| 11 | + "time" |
5 | 12 |
|
| 13 | + "github.com/flanksource/clicky" |
| 14 | + "github.com/flanksource/clicky/api" |
| 15 | + "github.com/flanksource/commons/console" |
| 16 | + commonsCtx "github.com/flanksource/commons/context" |
6 | 17 | "github.com/flanksource/commons/logger" |
7 | 18 | "github.com/flanksource/commons/logger/httpretty" |
8 | 19 | ) |
9 | 20 |
|
10 | | -func NewLogger(config TraceConfig) Middleware { |
11 | | - l := &httpretty.Logger{ |
12 | | - Time: config.Timing, |
13 | | - TLS: config.TLS, |
14 | | - RequestHeader: config.Headers, |
15 | | - RequestBody: config.Body, |
16 | | - ResponseHeader: config.ResponseHeaders, |
17 | | - ResponseBody: config.Body, |
18 | | - Auth: config.Auth, |
19 | | - Colors: true, // erase line if you don't like colors |
20 | | - Formatters: []httpretty.Formatter{&httpretty.JSONFormatter{}}, |
21 | | - } |
22 | | - |
23 | | - l.SkipHeader(logger.SensitiveHeaders) |
| 21 | +type jsonFormatter struct{} |
| 22 | + |
| 23 | +func (j *jsonFormatter) Match(mediatype string) bool { |
| 24 | + return strings.Contains(mediatype, "json") |
| 25 | +} |
| 26 | + |
| 27 | +func (j *jsonFormatter) Format(w io.Writer, src []byte) error { |
| 28 | + if !json.Valid(src) { |
| 29 | + if err := json.Unmarshal(src, &json.RawMessage{}); err != nil { |
| 30 | + return err |
| 31 | + } |
| 32 | + } |
| 33 | + var indented bytes.Buffer |
| 34 | + if err := json.Indent(&indented, src, "", " "); err != nil { |
| 35 | + return err |
| 36 | + } |
| 37 | + fmt.Fprint(w, api.CodeBlock("json", indented.String()).ANSI()) |
| 38 | + return nil |
| 39 | +} |
| 40 | + |
| 41 | +type formURLEncodedFormatter struct{} |
| 42 | + |
| 43 | +func (f *formURLEncodedFormatter) Match(mediatype string) bool { |
| 44 | + return mediatype == "application/x-www-form-urlencoded" |
| 45 | +} |
| 46 | + |
| 47 | +func (f *formURLEncodedFormatter) Format(w io.Writer, src []byte) error { |
| 48 | + values, err := url.ParseQuery(string(src)) |
| 49 | + if err != nil { |
| 50 | + return err |
| 51 | + } |
| 52 | + m := make(map[string]string) |
| 53 | + for k, v := range values { |
| 54 | + m[k] = strings.Join(v, ",") |
| 55 | + } |
| 56 | + fmt.Fprint(w, clicky.Map(m).ANSI()) |
| 57 | + return nil |
| 58 | +} |
| 59 | + |
| 60 | +func getLogger(req *http.Request) logger.Logger { |
| 61 | + if req == nil || req.Context() == nil { |
| 62 | + return logger.GetLogger() |
| 63 | + } |
| 64 | + return commonsCtx.LoggerFromContext(req.Context()) |
| 65 | +} |
| 66 | + |
| 67 | +func newContextLogger(config TraceConfig) Middleware { |
| 68 | + return func(rt http.RoundTripper) http.RoundTripper { |
| 69 | + l := &httpretty.Logger{ |
| 70 | + TLS: config.TLS, |
| 71 | + RequestHeader: config.Headers, |
| 72 | + RequestBody: config.Body, |
| 73 | + ResponseHeader: config.ResponseHeaders, |
| 74 | + ResponseBody: config.Response, |
| 75 | + Auth: config.Auth, |
| 76 | + Colors: true, |
| 77 | + Formatters: []httpretty.Formatter{&jsonFormatter{}, &formURLEncodedFormatter{}}, |
| 78 | + } |
| 79 | + l.SkipHeader(logger.SensitiveHeaders) |
| 80 | + |
| 81 | + var buf bytes.Buffer |
| 82 | + l.SetOutput(&buf) |
| 83 | + inner := l.RoundTripper(rt) |
| 84 | + |
| 85 | + return RoundTripperFunc(func(req *http.Request) (*http.Response, error) { |
| 86 | + buf.Reset() |
| 87 | + start := time.Now() |
| 88 | + resp, err := inner.RoundTrip(req) |
| 89 | + elapsed := time.Since(start) |
| 90 | + if buf.Len() > 0 { |
| 91 | + msg := buf.String() |
| 92 | + if config.Timing { |
| 93 | + suffix := "" |
| 94 | + if resp != nil { |
| 95 | + suffix = fmt.Sprintf(" %d", resp.StatusCode) |
| 96 | + } else if err != nil { |
| 97 | + suffix = " error" |
| 98 | + } |
| 99 | + suffix += fmt.Sprintf(" %s", elapsed.Truncate(time.Millisecond)) |
| 100 | + |
| 101 | + lines := strings.Split(msg, "\n") |
| 102 | + for i, line := range lines { |
| 103 | + if strings.Contains(line, req.Method) { |
| 104 | + lines[i] = strings.TrimRight(line, "\r\n") + suffix |
| 105 | + break |
| 106 | + } |
| 107 | + } |
| 108 | + msg = strings.Join(lines, "\n") |
| 109 | + } |
| 110 | + getLogger(req).Infof(strings.TrimSpace(msg)) |
| 111 | + } |
| 112 | + return resp, err |
| 113 | + }) |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +func statusColor(code int) func(string, ...interface{}) string { |
| 118 | + if code >= 200 && code < 300 { |
| 119 | + return console.Greenf |
| 120 | + } else if code >= 400 { |
| 121 | + return console.Redf |
| 122 | + } |
| 123 | + return console.Yellowf |
| 124 | +} |
| 125 | + |
| 126 | +func newContextAccessLog() Middleware { |
24 | 127 | return func(rt http.RoundTripper) http.RoundTripper { |
25 | | - return logger.NewHttpLogger(logger.GetLogger(), rt) |
| 128 | + return RoundTripperFunc(func(req *http.Request) (*http.Response, error) { |
| 129 | + start := time.Now() |
| 130 | + resp, err := rt.RoundTrip(req) |
| 131 | + elapsed := time.Since(start) |
| 132 | + log := getLogger(req) |
| 133 | + if err != nil { |
| 134 | + log.Infof("%s %s %s %s", console.Bluef(req.Method), console.Yellowf("%s", req.URL), console.Redf("error"), elapsed.Truncate(time.Millisecond)) |
| 135 | + return nil, err |
| 136 | + } |
| 137 | + log.Infof("%s %s %s %s", console.Bluef(req.Method), console.Yellowf("%s", req.URL), statusColor(resp.StatusCode)("%d", resp.StatusCode), elapsed.Truncate(time.Millisecond)) |
| 138 | + return resp, nil |
| 139 | + }) |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +func NewLogger(config TraceConfig) Middleware { |
| 144 | + if config.AccessLog { |
| 145 | + return newContextAccessLog() |
26 | 146 | } |
| 147 | + return newContextLogger(config) |
27 | 148 | } |
0 commit comments