Skip to content

Commit a5ed360

Browse files
authored
Merge pull request #221 from thirdweb-dev/06-09-replace_gin_logger_for_requests
replace gin logger for requests
2 parents 120b7e9 + 4c22ffb commit a5ed360

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

cmd/api.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func RunApi(cmd *cobra.Command, args []string) {
4848
defer stop()
4949

5050
r := gin.New()
51-
r.Use(gin.Logger())
51+
r.Use(middleware.Logger())
5252
r.Use(gin.Recovery())
5353

5454
// Add Swagger route

internal/middleware/logger.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package middleware
2+
3+
import (
4+
"time"
5+
6+
"github.com/gin-gonic/gin"
7+
"github.com/rs/zerolog/log"
8+
)
9+
10+
// Logger returns a gin.HandlerFunc (middleware) that logs requests using zerolog.
11+
func Logger() gin.HandlerFunc {
12+
return func(c *gin.Context) {
13+
// Start timer
14+
start := time.Now()
15+
path := c.Request.URL.Path
16+
raw := c.Request.URL.RawQuery
17+
18+
// Process request
19+
c.Next()
20+
21+
// Stop timer
22+
end := time.Now()
23+
latency := end.Sub(start)
24+
25+
// Get status code
26+
statusCode := c.Writer.Status()
27+
28+
// Get client IP
29+
clientIP := c.ClientIP()
30+
31+
// Get method
32+
method := c.Request.Method
33+
34+
// Get error message if any
35+
var errorMessage string
36+
if len(c.Errors) > 0 {
37+
errorMessage = c.Errors.String()
38+
}
39+
40+
log.Debug().
41+
Str("path", path).
42+
Str("raw", raw).
43+
Int("status", statusCode).
44+
Str("method", method).
45+
Str("ip", clientIP).
46+
Dur("latency", latency).
47+
Str("error", errorMessage).
48+
Msg("incoming request")
49+
}
50+
}

0 commit comments

Comments
 (0)