Skip to content

replace gin logger for requests #221

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func RunApi(cmd *cobra.Command, args []string) {
defer stop()

r := gin.New()
r.Use(gin.Logger())
r.Use(middleware.Logger())
r.Use(gin.Recovery())

// Add Swagger route
Expand Down
50 changes: 50 additions & 0 deletions internal/middleware/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package middleware

import (
"time"

"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
)

// Logger returns a gin.HandlerFunc (middleware) that logs requests using zerolog.
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
// Start timer
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery

// Process request
c.Next()

// Stop timer
end := time.Now()
latency := end.Sub(start)

// Get status code
statusCode := c.Writer.Status()

// Get client IP
clientIP := c.ClientIP()

// Get method
method := c.Request.Method

// Get error message if any
var errorMessage string
if len(c.Errors) > 0 {
errorMessage = c.Errors.String()
}

log.Debug().
Str("path", path).
Str("raw", raw).
Int("status", statusCode).
Str("method", method).
Str("ip", clientIP).
Dur("latency", latency).
Str("error", errorMessage).
Msg("incoming request")
}
}