Skip to content

Commit

Permalink
Link logger with gin context.
Browse files Browse the repository at this point in the history
  • Loading branch information
cedric-appdirect committed Jan 8, 2024
1 parent 7bec240 commit fdbfb8b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
26 changes: 19 additions & 7 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ type config struct {
serverErrorLevel zerolog.Level
}

const loggerKey = "_gin-contrib/logger_"

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

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

c.Next()
track := true

if _, ok := skip[path]; ok {
track = false
}
Expand All @@ -97,6 +97,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 All @@ -106,11 +117,7 @@ func SetLogger(opts ...Option) gin.HandlerFunc {

l = l.With().
Int("status", c.Writer.Status()).
Str("method", c.Request.Method).
Str("path", path).
Str("ip", c.ClientIP()).
Dur("latency", latency).
Str("user_agent", c.Request.UserAgent()).Logger()
Dur("latency", latency).Logger()

msg := "Request"
if len(c.Errors) > 0 {
Expand Down Expand Up @@ -141,3 +148,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 @@ -67,6 +67,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 fdbfb8b

Please sign in to comment.