Skip to content

feat: add option to omit query string from path matching and logging #110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,23 @@ func main() {
})
}

// Example of WithPathNoQuery usage
Copy link
Preview

Copilot AI May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Consider adding a sample of the actual logged output after this example block. Showing how path and query fields appear will make the feature's effect more concrete.

Copilot uses AI. Check for mistakes.

nq := r.Group("/no-query", logger.SetLogger(
logger.WithPathNoQuery(true),
logger.WithPathLevel(map[string]zerolog.Level{
// normally this wouldn't match /no-query/boring?foo, but WithPathNoQuery(true) makes it match
"/no-query/boring": zerolog.DebugLevel,
}),
))
{
nq.GET("/boring", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
nq.GET("/interesting", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
}

// 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
17 changes: 17 additions & 0 deletions _example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,23 @@ func main() {
})
}

// Example of WithPathNoQuery usage
nq := r.Group("/no-query", logger.SetLogger(
logger.WithPathNoQuery(true),
logger.WithPathLevel(map[string]zerolog.Level{
// normally this wouldn't match /no-query/boring?foo, but WithPathNoQuery(true) makes it match
"/no-query/boring": zerolog.DebugLevel,
}),
))
{
nq.GET("/boring", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
nq.GET("/interesting", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
}

// 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
27 changes: 21 additions & 6 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ type config struct {
pathLevels is a map of specific paths to log levels for requests with status code < 400.
*/
pathLevels map[string]zerolog.Level
/*
pathNoQuery specifies if the path should be handled without the query
string for both logging and matching against pathLevels. If enabled, the
query string will be logged in its own field.
*/
pathNoQuery bool
/*
message is a custom string that sets a log-message when http-request has finished
*/
Expand Down Expand Up @@ -157,17 +163,22 @@ func SetLogger(opts ...Option) gin.HandlerFunc {

start := time.Now()
path := c.Request.URL.Path
if raw := c.Request.URL.RawQuery; raw != "" {
path += "?" + raw
rawQuery := c.Request.URL.RawQuery
Copy link
Preview

Copilot AI May 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The logic for extracting and handling the query string is duplicated in two places. Extracting path and query parsing into a small helper function would reduce duplication and improve maintainability.

Copilot uses AI. Check for mistakes.

if rawQuery != "" && !cfg.pathNoQuery {
path += "?" + rawQuery
}

track := !shouldSkipLogging(path, skip, cfg, c)

contextLogger := rl
if track {
contextLogger = rl.With().
rlc := rl.With().
Str("method", c.Request.Method).
Str("path", path).
Str("path", path)
if cfg.pathNoQuery && rawQuery != "" {
rlc = rlc.Str("query", rawQuery)
}
contextLogger = rlc.
Str("ip", c.ClientIP()).
Str("user_agent", c.Request.UserAgent()).
Logger()
Expand All @@ -194,10 +205,14 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
evt = cfg.context(c, evt)
}

evt.
evt = evt.
Int("status", c.Writer.Status()).
Str("method", c.Request.Method).
Str("path", path).
Str("path", path)
if cfg.pathNoQuery && rawQuery != "" {
evt = evt.Str("query", rawQuery)
}
evt.
Str("ip", c.ClientIP()).
Dur("latency", latency).
Str("user_agent", c.Request.UserAgent()).
Expand Down
37 changes: 37 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,43 @@ func TestLoggerCustomMessageWithErrors(t *testing.T) {
assert.Equal(t, strings.Count(buffer.String(), " with errors: "), 1)
}

func TestLoggerPathNoQuery(t *testing.T) {
buffer := new(bytes.Buffer)
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(SetLogger(
WithWriter(buffer),
WithPathNoQuery(true),
WithPathLevel(map[string]zerolog.Level{
"/example2": zerolog.WarnLevel,
}),
))
r.GET("/example", func(c *gin.Context) {
l := Get(c)
l.Debug().Msg("contextlogger")
})
r.GET("/example2", func(c *gin.Context) {})

performRequest(r, "GET", "/example?foo=bar")
lines := strings.Split(strings.TrimSpace(buffer.String()), "\n")
assert.Len(t, lines, 2)
for i, line := range lines {
assert.Contains(t, line, " query=foo=bar ", "line %d", i)
}

// with no query string, the field should be omitted
buffer.Reset()
performRequest(r, "GET", "/example")
assert.NotContains(t, buffer.String(), "query=")

buffer.Reset()
performRequest(r, "GET", "/example2?foo=bar")
// this one should be logged at warn level because the query-free path matches
// the level map entry
assert.Contains(t, buffer.String(), "WRN")
assert.Contains(t, buffer.String(), " query=foo=bar ")
}

func BenchmarkLogger(b *testing.B) {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
Expand Down
6 changes: 6 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,3 +269,9 @@ func WithSpecificLogLevelByStatusCode(statusCodes map[int]zerolog.Level) Option
c.specificLevelByStatusCode = statusCodes
})
}

func WithPathNoQuery(b bool) Option {
return optionFunc(func(c *config) {
c.pathNoQuery = b
})
}
Loading