Skip to content

Commit

Permalink
feat: add skipper functionality to logger (#80)
Browse files Browse the repository at this point in the history
- Add skipper usage example in README.md
- Add `skip` field to logger config struct
- Modify `SetLogger` function to use the `skip` field
- Add `skipper` type and `WithSkipper` option function to logger.go
- Add tests for skipper functionality in logger_test.go
- Add `WithSkipper` option function to options.go

Signed-off-by: appleboy <[email protected]>
  • Loading branch information
appleboy authored Feb 2, 2024
1 parent 5b0d125 commit 637bb30
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 2 deletions.
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
})
}

0 comments on commit 637bb30

Please sign in to comment.