Skip to content
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

feat: add skipper functionality to logger #80

Merged
merged 1 commit into from
Feb 2, 2024
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
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,15 @@ func main() {
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})

// Example of skipper usage
r.GET("/health", logger.SetLogger(
logger.WithSkipper(func(c *gin.Context) bool {
return c.Request.URL.Path == "/health"
}),
), func(c *gin.Context) {
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})

// Listen and Server in 0.0.0.0:8080
if err := r.Run(":8080"); err != nil {
log.Fatal().Msg("can' start server with 8080 port")
Expand Down
12 changes: 10 additions & 2 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,19 @@ import (

type Fn func(*gin.Context, zerolog.Logger) zerolog.Logger

// Skipper is a function to skip logs based on provided Context
type Skipper func(c *gin.Context) bool

// Config defines the config for logger middleware
type config struct {
logger Fn
// UTC a boolean stating whether to use UTC time zone or local.
utc bool
skipPath []string
skipPathRegexps []*regexp.Regexp
// skip is a Skipper that indicates which logs should not be written.
// Optional.
skip Skipper
// Output is a writer where logs are written.
// Optional. Default value is gin.DefaultWriter.
output io.Writer
Expand Down Expand Up @@ -84,7 +90,7 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
c.Next()
track := true

if _, ok := skip[path]; ok {
if _, ok := skip[path]; ok || (cfg.skip != nil && cfg.skip(c)) {
track = false
}

Expand Down Expand Up @@ -112,7 +118,9 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
Str("path", path).
Str("ip", c.ClientIP()).
Dur("latency", latency).
Str("user_agent", c.Request.UserAgent()).Logger()
Str("user_agent", c.Request.UserAgent()).
Int("body_size", c.Writer.Size()).
Logger()

msg := "Request"
if len(c.Errors) > 0 {
Expand Down
23 changes: 23 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,29 @@ func TestLoggerCustomLevel(t *testing.T) {
assert.Contains(t, buffer.String(), "FTL")
}

func TestLoggerSkipper(t *testing.T) {
buffer := new(bytes.Buffer)
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(SetLogger(
WithWriter(buffer),
WithSkipper(func(c *gin.Context) bool {
return c.Request.URL.Path == "/example2"
}),
))
r.GET("/example", func(c *gin.Context) {})
r.GET("/example2", func(c *gin.Context) {})

performRequest(r, "GET", "/example")
assert.Contains(t, buffer.String(), "GET")
assert.Contains(t, buffer.String(), "/example")

buffer.Reset()
performRequest(r, "GET", "/example2")
assert.NotContains(t, buffer.String(), "GET")
assert.NotContains(t, buffer.String(), "/example2")
}

func BenchmarkLogger(b *testing.B) {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
Expand Down
9 changes: 9 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,12 @@ func WithServerErrorLevel(lvl zerolog.Level) Option {
c.serverErrorLevel = lvl
})
}

// WithSkipper set function to skip middleware
// requests with this function returning true will not have their logs written
// Default is nil
func WithSkipper(s Skipper) Option {
return optionFunc(func(c *config) {
c.skip = s
})
}
Loading