Skip to content

Commit

Permalink
chore: link logger with gin context. (#76)
Browse files Browse the repository at this point in the history
Co-authored-by: Bo-Yi Wu <[email protected]>
  • Loading branch information
cedric-appdirect and appleboy authored Nov 8, 2024
1 parent 9c6ff65 commit 1cd04f4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
19 changes: 18 additions & 1 deletion logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ type config struct {
pathLevels map[string]zerolog.Level
}

const loggerKey = "_gin-contrib/logger_"

var isTerm bool = isatty.IsTerminal(os.Stdout.Fd())

// SetLogger initializes the logging middleware.
Expand Down Expand Up @@ -88,7 +90,6 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
path = path + "?" + raw
}

c.Next()
track := true

if _, ok := skip[path]; ok || (cfg.skip != nil && cfg.skip(c)) {
Expand All @@ -106,6 +107,17 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
}
}

if track {
l = l.With().
Str("method", c.Request.Method).
Str("path", path).
Str("ip", c.ClientIP()).
Str("user_agent", c.Request.UserAgent()).Logger()
}
c.Set(loggerKey, l)

c.Next()

if track {
end := time.Now()
if cfg.utc {
Expand Down Expand Up @@ -149,3 +161,8 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
func ParseLevel(levelStr string) (zerolog.Level, error) {
return zerolog.ParseLevel(levelStr)
}

// Get return the logger associated with a gin context
func Get(c *gin.Context) zerolog.Logger {
return c.MustGet(loggerKey).(zerolog.Logger)
}
11 changes: 11 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,17 @@ func TestLogger(t *testing.T) {
assert.Contains(t, buffer.String(), "/example")
assert.Contains(t, buffer.String(), "ERR")
assert.Contains(t, buffer.String(), "path=/example?a=100")

buffer.Reset()
r.GET("/example-with-additional-log", func(ctx *gin.Context) {
l := Get(ctx)
l.Info().Msg("additional log")
})
performRequest(r, "GET", "/example-with-additional-log")
assert.Contains(t, buffer.String(), "200")
assert.Contains(t, buffer.String(), "GET")
assert.Contains(t, buffer.String(), "/example-with-additional-log")
assert.Contains(t, buffer.String(), "additional log")
}

func TestLoggerWithLogger(t *testing.T) {
Expand Down

0 comments on commit 1cd04f4

Please sign in to comment.