-
Notifications
You must be signed in to change notification settings - Fork 10
/
logger.go
59 lines (47 loc) · 1.55 KB
/
logger.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
// Package echologrus provides a middleware for echo that logs request details
// via the logrus logging library
package echologrus // fknsrs.biz/p/echo-logrus
import (
"fmt"
"net/http"
"time"
"github.com/Sirupsen/logrus"
"github.com/labstack/echo"
)
// New returns a new middleware handler with a default name and logger
func New() echo.MiddlewareFunc {
return NewWithName("web")
}
// NewWithName returns a new middleware handler with the specified name
func NewWithName(name string) echo.MiddlewareFunc {
return NewWithNameAndLogger(name, logrus.StandardLogger())
}
// NewWithNameAndLogger returns a new middleware handler with the specified name
// and logger
func NewWithNameAndLogger(name string, l *logrus.Logger) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
start := time.Now()
entry := l.WithFields(logrus.Fields{
"request": c.Request().RequestURI,
"method": c.Request().Method,
"remote": c.Request().RemoteAddr,
})
if reqID := c.Request().Header.Get("X-Request-Id"); reqID != "" {
entry = entry.WithField("request_id", reqID)
}
entry.Info("started handling request")
if err := next(c); err != nil {
c.Error(err)
}
latency := time.Since(start)
entry.WithFields(logrus.Fields{
"status": c.Response().Status(),
"text_status": http.StatusText(c.Response().Status()),
"took": latency,
fmt.Sprintf("measure#%s.latency", name): latency.Nanoseconds(),
}).Info("completed handling request")
return nil
}
}
}