...
1
2
3
4 package ginrus
5
6 import (
7 "time"
8
9 "github.com/gin-gonic/gin"
10 "github.com/sirupsen/logrus"
11 )
12
13 type loggerEntryWithFields interface {
14 WithFields(fields logrus.Fields) *logrus.Entry
15 }
16
17
18
19
20
21
22
23
24
25 func Ginrus(logger loggerEntryWithFields, timeFormat string, utc bool) gin.HandlerFunc {
26 return func(c *gin.Context) {
27 start := time.Now()
28
29 path := c.Request.URL.Path
30 c.Next()
31
32 end := time.Now()
33 latency := end.Sub(start)
34 if utc {
35 end = end.UTC()
36 }
37
38 entry := logger.WithFields(logrus.Fields{
39 "status": c.Writer.Status(),
40 "method": c.Request.Method,
41 "path": path,
42 "ip": c.ClientIP(),
43 "latency": latency,
44 "user-agent": c.Request.UserAgent(),
45 "time": end.Format(timeFormat),
46 })
47
48 if len(c.Errors) > 0 {
49
50 entry.Error(c.Errors.String())
51 } else {
52 entry.Info()
53 }
54 }
55 }
56
View as plain text