-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogger.go
52 lines (40 loc) · 961 Bytes
/
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
package ginzerolog
import (
"io"
"time"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog"
)
//Logger function is gin middleware to use zerolog
func Logger() gin.HandlerFunc {
return LoggerWithWriter(gin.DefaultWriter)
}
func LoggerWithWriter(out io.Writer) gin.HandlerFunc {
log := zerolog.New(out).With().Timestamp().Logger()
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
// Process request
c.Next()
latency := time.Since(start)
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
comment := c.Errors.ByType(gin.ErrorTypePrivate).String()
if raw != "" {
path = path + "?" + raw
}
event := log.Info()
if comment != "" {
event = log.Error()
}
event.
Int("statusCode", statusCode).
Dur("latency", latency).
Str("clientIP", clientIP).
Str("method", method).
Str("path", path).
Msg(comment)
}
}