Skip to content

Commit 1cd04f4

Browse files
chore: link logger with gin context. (#76)
Co-authored-by: Bo-Yi Wu <[email protected]>
1 parent 9c6ff65 commit 1cd04f4

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

logger.go

+18-1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ type config struct {
4040
pathLevels map[string]zerolog.Level
4141
}
4242

43+
const loggerKey = "_gin-contrib/logger_"
44+
4345
var isTerm bool = isatty.IsTerminal(os.Stdout.Fd())
4446

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

91-
c.Next()
9293
track := true
9394

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

110+
if track {
111+
l = l.With().
112+
Str("method", c.Request.Method).
113+
Str("path", path).
114+
Str("ip", c.ClientIP()).
115+
Str("user_agent", c.Request.UserAgent()).Logger()
116+
}
117+
c.Set(loggerKey, l)
118+
119+
c.Next()
120+
109121
if track {
110122
end := time.Now()
111123
if cfg.utc {
@@ -149,3 +161,8 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
149161
func ParseLevel(levelStr string) (zerolog.Level, error) {
150162
return zerolog.ParseLevel(levelStr)
151163
}
164+
165+
// Get return the logger associated with a gin context
166+
func Get(c *gin.Context) zerolog.Logger {
167+
return c.MustGet(loggerKey).(zerolog.Logger)
168+
}

logger_test.go

+11
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,17 @@ func TestLogger(t *testing.T) {
7070
assert.Contains(t, buffer.String(), "/example")
7171
assert.Contains(t, buffer.String(), "ERR")
7272
assert.Contains(t, buffer.String(), "path=/example?a=100")
73+
74+
buffer.Reset()
75+
r.GET("/example-with-additional-log", func(ctx *gin.Context) {
76+
l := Get(ctx)
77+
l.Info().Msg("additional log")
78+
})
79+
performRequest(r, "GET", "/example-with-additional-log")
80+
assert.Contains(t, buffer.String(), "200")
81+
assert.Contains(t, buffer.String(), "GET")
82+
assert.Contains(t, buffer.String(), "/example-with-additional-log")
83+
assert.Contains(t, buffer.String(), "additional log")
7384
}
7485

7586
func TestLoggerWithLogger(t *testing.T) {

0 commit comments

Comments
 (0)