Skip to content

Commit

Permalink
feat: added option to disable default field and enable latency
Browse files Browse the repository at this point in the history
  • Loading branch information
aleksasiriski committed Feb 4, 2024
1 parent e6115f7 commit 03a8314
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
28 changes: 19 additions & 9 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ type config struct {
serverErrorLevel zerolog.Level
// the log level to use for a specific path with status code < 400
pathLevels map[string]zerolog.Level
// should default field be used
disableDefaultFields bool
// should latency be logged as a field
latency bool
}

var isTerm bool = isatty.IsTerminal(os.Stdout.Fd())
Expand Down Expand Up @@ -112,15 +116,21 @@ func SetLogger(opts ...Option) gin.HandlerFunc {
}
latency := end.Sub(start)

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()).
Int("body_size", c.Writer.Size()).
Logger()
if !cfg.disableDefaultFields {
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()).
Int("body_size", c.Writer.Size()).
Logger()
} else if cfg.latency {
l = l.With().
Dur("latency", latency).
Logger()
}

msg := "Request"
if len(c.Errors) > 0 {
Expand Down
18 changes: 18 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,21 @@ func WithSkipper(s Skipper) Option {
c.skip = s
})
}

// WithDefaultFieldsDisabled disabled default fields
// This includes latency field
// Default is false
func WithDefaultFieldsDisabled() Option {
return optionFunc(func(c *config) {
c.disableDefaultFields = true
})
}

// WithLatency sets latency field logging
// This is ignored when WithDefaultFieldsDisabled is omitted
// Default is false
func WithLatency() Option {
return optionFunc(func(c *config) {
c.latency = true
})
}

0 comments on commit 03a8314

Please sign in to comment.