Skip to content

Commit

Permalink
feat: logging data from gin.Context (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
laggu authored Nov 29, 2024
1 parent a53e96f commit 637ac38
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
12 changes: 12 additions & 0 deletions _example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"math/rand"
"net/http"
"regexp"
"time"
Expand Down Expand Up @@ -117,6 +118,17 @@ func main() {
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})

// Example of logging data on gin.Context
r.GET("/context", logger.SetLogger(
logger.WithContext(func(c *gin.Context, e *zerolog.Event) *zerolog.Event {
return e.Any("data1", c.MustGet("data1")).Any("data2", c.MustGet("data2"))
}),
), func(c *gin.Context) {
c.Set("data1", rand.Intn(100))
c.Set("data2", rand.Intn(100))
c.String(http.StatusOK, "pong "+fmt.Sprint(time.Now().Unix()))
})

// Example of skipper usage
v1 := r.Group("/v1", logger.SetLogger(
logger.WithSkipper(func(c *gin.Context) bool {
Expand Down
7 changes: 7 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import (
// within the context of a Gin HTTP request.
type Fn func(*gin.Context, zerolog.Logger) zerolog.Logger

type EventFn func(*gin.Context, *zerolog.Event) *zerolog.Event

// Skipper defines a function to skip middleware. It takes a gin.Context as input
// and returns a boolean indicating whether to skip the middleware for the given context.
type Skipper func(c *gin.Context) bool
Expand All @@ -25,6 +27,8 @@ type Skipper func(c *gin.Context) bool
type config struct {
// logger is a function that defines the logging behavior.
logger Fn
// context is a function that defines the logging behavior of gin.Context data
context EventFn
// utc is a boolean stating whether to use UTC time zone or local.
utc bool
// skipPath is a list of paths to be skipped from logging.
Expand Down Expand Up @@ -175,6 +179,9 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
default:
evt = rl.WithLevel(cfg.defaultLevel).Ctx(c)
}
if cfg.context != nil {
evt = cfg.context(c, evt)
}
evt.
Int("status", c.Writer.Status()).
Str("method", c.Request.Method).
Expand Down
6 changes: 6 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,9 @@ func WithSkipper(s Skipper) Option {
c.skip = s
})
}

func WithContext(fn func(*gin.Context, *zerolog.Event) *zerolog.Event) Option {
return optionFunc(func(c *config) {
c.context = fn
})
}

0 comments on commit 637ac38

Please sign in to comment.