|
| 1 | +package util |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "os" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/felixge/httpsnoop" |
| 9 | + "github.com/rs/zerolog" |
| 10 | + "github.com/rs/zerolog/log" |
| 11 | +) |
| 12 | + |
| 13 | +type LogRequestHandlerOptions struct { |
| 14 | + Pretty bool |
| 15 | +} |
| 16 | + |
| 17 | +// LogReqInfo describes info about HTTP request |
| 18 | +type HTTPReqInfo struct { |
| 19 | + // GET etc. |
| 20 | + method string |
| 21 | + // requested path |
| 22 | + path string |
| 23 | + // response code, like 200, 404 |
| 24 | + code int |
| 25 | + // number of bytes of the response sent |
| 26 | + size int64 |
| 27 | + // how long did it take to |
| 28 | + duration time.Duration |
| 29 | + // client IP Address |
| 30 | + ipAddress string |
| 31 | + // client UserAgent |
| 32 | + userAgent string |
| 33 | + // referer header |
| 34 | + referer string |
| 35 | +} |
| 36 | + |
| 37 | +func logHTTPReqInfo(ri *HTTPReqInfo) { |
| 38 | + log.Info(). |
| 39 | + Str("method", ri.method). |
| 40 | + Str("path", ri.path). |
| 41 | + Int("code", ri.code). |
| 42 | + Int64("size", ri.size). |
| 43 | + Dur("duration", ri.duration). |
| 44 | + Str("ipAddress", ri.ipAddress). |
| 45 | + Str("userAgent", ri.userAgent). |
| 46 | + Str("referer", ri.referer). |
| 47 | + Send() |
| 48 | +} |
| 49 | + |
| 50 | +func LogRequestHandler(h http.Handler, opt *LogRequestHandlerOptions) http.Handler { |
| 51 | + if opt.Pretty { |
| 52 | + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) |
| 53 | + } |
| 54 | + |
| 55 | + zerolog.DurationFieldUnit = time.Millisecond |
| 56 | + |
| 57 | + fn := func(w http.ResponseWriter, r *http.Request) { |
| 58 | + // runs handler h and captures information about HTTP request |
| 59 | + mtr := httpsnoop.CaptureMetrics(h, w, r) |
| 60 | + |
| 61 | + logHTTPReqInfo(&HTTPReqInfo{ |
| 62 | + method: r.Method, |
| 63 | + path: r.URL.String(), |
| 64 | + code: mtr.Code, |
| 65 | + size: mtr.Written, |
| 66 | + duration: mtr.Duration, |
| 67 | + ipAddress: requestGetRemoteAddress(r), |
| 68 | + userAgent: r.Header.Get("User-Agent"), |
| 69 | + referer: r.Header.Get("Referer"), |
| 70 | + }) |
| 71 | + } |
| 72 | + |
| 73 | + return http.HandlerFunc(fn) |
| 74 | +} |
0 commit comments