-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathlogger.go
More file actions
56 lines (45 loc) · 1.16 KB
/
Copy pathlogger.go
File metadata and controls
56 lines (45 loc) · 1.16 KB
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
package middleware
import (
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// InitLogger initializes zerolog with level from LOG_LEVEL env var
func InitLogger() {
level := os.Getenv("LOG_LEVEL")
if level == "" {
level = "info"
}
parsedLevel, err := zerolog.ParseLevel(level)
if err != nil {
parsedLevel = zerolog.InfoLevel
}
zerolog.SetGlobalLevel(parsedLevel)
log.Logger = zerolog.New(os.Stdout).
With().
Timestamp().
Logger()
}
// RequestLogger is a Gin middleware that logs each request in JSON
func RequestLogger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
// Process request
c.Next()
latency := time.Since(start)
// Optional values set by handlers
paymentVerified, _ := c.Get("payment_verified")
userWallet, _ := c.Get("user_wallet")
log.Info().
Str("method", c.Request.Method).
Str("path", c.Request.URL.Path).
Int("status", c.Writer.Status()).
Int64("latency_ms", latency.Milliseconds()).
Str("client_ip", c.ClientIP()).
Interface("payment_verified", paymentVerified).
Interface("user_wallet", userWallet).
Msg("request completed")
}
}