Skip to content

Commit

Permalink
chore(level): make log level configurable (#53)
Browse files Browse the repository at this point in the history
* Make log level configurable

* fix build

---------

Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
  • Loading branch information
rymurr and appleboy committed Nov 27, 2023
1 parent 1358676 commit a63110e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
18 changes: 12 additions & 6 deletions zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@ type ZapLogger interface {

// Config is config setting for Ginzap
type Config struct {
TimeFormat string
UTC bool
SkipPaths []string
Context Fn
TimeFormat string
UTC bool
SkipPaths []string
Context Fn
DefaultLevel zapcore.Level
}

// Ginzap returns a gin.HandlerFunc (middleware) that logs requests using uber-go/zap.
Expand All @@ -41,7 +42,7 @@ type Config struct {
// 1. A time package format string (e.g. time.RFC3339).
// 2. A boolean stating whether to use UTC time zone or local.
func Ginzap(logger ZapLogger, timeFormat string, utc bool) gin.HandlerFunc {
return GinzapWithConfig(logger, &Config{TimeFormat: timeFormat, UTC: utc})
return GinzapWithConfig(logger, &Config{TimeFormat: timeFormat, UTC: utc, DefaultLevel: zapcore.InfoLevel})
}

// GinzapWithConfig returns a gin.HandlerFunc using configs
Expand Down Expand Up @@ -88,7 +89,12 @@ func GinzapWithConfig(logger ZapLogger, conf *Config) gin.HandlerFunc {
logger.Error(e, fields...)
}
} else {
logger.Info(path, fields...)
zl, ok := logger.(*zap.Logger)
if ok {
zl.Log(conf.DefaultLevel, path, fields...)
} else {
logger.Error(path, fields...)
}
}
}
}
Expand Down
12 changes: 9 additions & 3 deletions zap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/gin-gonic/gin"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
)

Expand Down Expand Up @@ -83,9 +84,10 @@ func TestGinzapWithConfig(t *testing.T) {

utcLogger, utcLoggerObserved := buildDummyLogger()
r.Use(GinzapWithConfig(utcLogger, &Config{
TimeFormat: time.RFC3339,
UTC: true,
SkipPaths: []string{"/no_log"},
TimeFormat: time.RFC3339,
UTC: true,
SkipPaths: []string{"/no_log"},
DefaultLevel: zapcore.WarnLevel,
}))

r.GET("/test", func(c *gin.Context) {
Expand Down Expand Up @@ -122,4 +124,8 @@ func TestGinzapWithConfig(t *testing.T) {
if err != nil {
t.Fatal(err)
}

if logLine.Level != zapcore.WarnLevel {
t.Fatalf("log level should be warn but was %s", logLine.Level.String())
}
}

0 comments on commit a63110e

Please sign in to comment.