|
| 1 | +package middleware |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "io/ioutil" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/jeferagudeloc/grpc-http-gateway/src/gateway/application/adapter/logger" |
| 11 | + "github.com/jeferagudeloc/grpc-http-gateway/src/gateway/application/adapter/logging" |
| 12 | + "github.com/pkg/errors" |
| 13 | + "github.com/urfave/negroni" |
| 14 | +) |
| 15 | + |
| 16 | +type Logger struct { |
| 17 | + log logger.Logger |
| 18 | +} |
| 19 | + |
| 20 | +func NewLogger(log logger.Logger) Logger { |
| 21 | + return Logger{log: log} |
| 22 | +} |
| 23 | + |
| 24 | +func (l Logger) Execute(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { |
| 25 | + start := time.Now() |
| 26 | + |
| 27 | + const ( |
| 28 | + logKey = "logger_middleware" |
| 29 | + requestKey = "api_request" |
| 30 | + responseKey = "api_response" |
| 31 | + ) |
| 32 | + |
| 33 | + body, err := getRequestPayload(r) |
| 34 | + if err != nil { |
| 35 | + logging.NewError( |
| 36 | + l.log, |
| 37 | + err, |
| 38 | + logKey, |
| 39 | + http.StatusBadRequest, |
| 40 | + ).Log("error when getting payload") |
| 41 | + |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + l.log.WithFields(logger.Fields{ |
| 46 | + "key": requestKey, |
| 47 | + "payload": body, |
| 48 | + "url": r.URL.Path, |
| 49 | + "http_method": r.Method, |
| 50 | + }).Infof("started handling request") |
| 51 | + |
| 52 | + next.ServeHTTP(w, r) |
| 53 | + |
| 54 | + end := time.Since(start).Seconds() |
| 55 | + res := w.(negroni.ResponseWriter) |
| 56 | + l.log.WithFields(logger.Fields{ |
| 57 | + "key": responseKey, |
| 58 | + "url": r.URL.Path, |
| 59 | + "http_method": r.Method, |
| 60 | + "http_status": res.Status(), |
| 61 | + "response_time": end, |
| 62 | + }).Infof("completed handling request") |
| 63 | +} |
| 64 | + |
| 65 | +func getRequestPayload(r *http.Request) (string, error) { |
| 66 | + if r.Body == nil { |
| 67 | + return "", errors.New("body not defined") |
| 68 | + } |
| 69 | + |
| 70 | + payload, err := ioutil.ReadAll(r.Body) |
| 71 | + if err != nil { |
| 72 | + return "", errors.Wrap(err, "error read body") |
| 73 | + } |
| 74 | + |
| 75 | + r.Body = ioutil.NopCloser(bytes.NewBuffer(payload)) |
| 76 | + |
| 77 | + return strings.TrimSpace(string(payload)), nil |
| 78 | +} |
0 commit comments