-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging.go
53 lines (40 loc) · 1.01 KB
/
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
package main
import (
"os"
"time"
"github.com/labstack/echo"
log "github.com/sirupsen/logrus"
)
// initLogging sets up logger with
// appropriate logging level
func initLogging(lvl log.Level) {
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
log.SetLevel(lvl)
log.SetReportCaller(true)
}
// LogRequest is middleware function that logs handlers performance
// and outputs req/rsp meta data
func LogRequest(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
//get the objects
req := c.Request()
res := c.Response()
start := time.Now()
// wait while handler will be processed
if err = next(c); err != nil {
log.Error(err.Error())
c.Error(err)
}
// calculate the time and add it to the log
stop := time.Now()
log.WithFields(log.Fields{
"method": req.Method,
"remote_ip": c.RealIP(),
"uri": req.RequestURI,
"status": res.Status,
"latency": stop.Sub(start).String(),
}).Info("request processed")
return nil
}
}