-
Notifications
You must be signed in to change notification settings - Fork 4
/
logger.go
40 lines (32 loc) · 1.06 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
package middleware
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog"
)
func NewLogger(baseLogger zerolog.Logger) func(*gin.Context) {
logger := baseLogger.With().Str("module", "http").Logger()
return func(c *gin.Context) {
start := time.Now()
c.Next()
latency := time.Since(start)
// path := c.FullPath()
path := c.Request.URL.Path
dumplogger := logger.With().
Str("method", c.Request.Method).
Str("path", path).
Dur("latency", latency). // keep this for log aggregation, where number is better than user-readable string
Str("latency_str", latency.String()). // user-readable latency
Int("status_code", c.Writer.Status()).
Str("ip", c.ClientIP()).Logger()
switch {
case c.Writer.Status() >= http.StatusBadRequest && c.Writer.Status() < http.StatusInternalServerError:
dumplogger.Warn().Msg("HTTP request handled")
case c.Writer.Status() >= http.StatusInternalServerError:
dumplogger.Error().Msg("HTTP request handled")
default:
dumplogger.Trace().Msg("HTTP request handled")
}
}
}