Skip to content

Commit

Permalink
feat: remove encoder options (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
shipengqi authored Sep 6, 2023
1 parent 55833fa commit 6283da1
Show file tree
Hide file tree
Showing 7 changed files with 55 additions and 80 deletions.
1 change: 1 addition & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ jobs:
- name: codecov
uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
flags: unittests
fail_ci_if_error: true
files: coverage.out
39 changes: 0 additions & 39 deletions encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,45 +11,6 @@ import (
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)

type Encoder interface {
apply(l *Logger)
}

// encoderFunc wraps a func so it satisfies the Encoder interface.
type encoderFunc func(*Logger)

func (f encoderFunc) apply(l *Logger) {
f(l)
}

// WithFilenameEncoder is used to set the log filename encoder.
func WithFilenameEncoder(encoder FilenameEncoder) Encoder {
return encoderFunc(func(l *Logger) {
l.filenameEncoder = encoder
})
}

// WithTimeEncoder is used to set the log time encoder.
func WithTimeEncoder(encoder TimeEncoder) Encoder {
return encoderFunc(func(l *Logger) {
l.timeEncoder = encoder
})
}

// WithLevelEncoder is used to set the log level encoder.
func WithLevelEncoder(encoder LevelEncoder) Encoder {
return encoderFunc(func(l *Logger) {
l.levelEncoder = encoder
})
}

// WithCallerEncoder is used to set the log caller encoder.
func WithCallerEncoder(encoder CallerEncoder) Encoder {
return encoderFunc(func(l *Logger) {
l.callerEncoder = encoder
})
}

// FilenameEncoder log filename encoder,
// return the full name of the log file.
type FilenameEncoder func() string
Expand Down
4 changes: 2 additions & 2 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ type Interface interface {
}

// Configure sets up the global logger.
func Configure(opts *Options, encoders ...Encoder) {
l := New(opts, encoders...)
func Configure(opts *Options) {
l := New(opts)
_globalL = l
zap.RedirectStdLog(_globalL.log)
}
Expand Down
27 changes: 14 additions & 13 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,16 +134,17 @@ func TestGlobalLogger(t *testing.T) {
opts.ConsoleLevel = DebugLevel.String()
opts.DisableConsoleColor = true
opts.DisableConsoleCaller = false
Configure(opts, WithLevelEncoder(zapcore.LowercaseLevelEncoder))
opts.LevelEncoder = zapcore.LowercaseLevelEncoder
Configure(opts)
L().Debugf("Hello, %s", name+"1")
L().Infof("Hello, %s", name+"2")
L().Warnf("Hello, %s", name+"3")
L().Errorf("Hello, %s", name+"4")
expected := []string{
"debug log/log_test.go:138 Hello, world1",
"info log/log_test.go:139 Hello, world2",
"warn log/log_test.go:140 Hello, world3",
"error log/log_test.go:141 Hello, world4",
"debug log/log_test.go:139 Hello, world1",
"info log/log_test.go:140 Hello, world2",
"warn log/log_test.go:141 Hello, world3",
"error log/log_test.go:142 Hello, world4",
}
_ = w.Close()
stdout, _ := io.ReadAll(r)
Expand Down Expand Up @@ -172,10 +173,9 @@ func TestGlobalLogger(t *testing.T) {
opts.DisableConsoleColor = true
opts.DisableConsoleCaller = false
opts.CallerSkip = -1
Configure(opts,
WithLevelEncoder(zapcore.LowercaseLevelEncoder),
WithCallerEncoder(zapcore.ShortCallerEncoder),
)
opts.LevelEncoder = zapcore.LowercaseLevelEncoder
opts.CallerEncoder = zapcore.ShortCallerEncoder
Configure(opts)
L().Debugf("Hello, %s", name+"1")
L().Infof("Hello, %s", name+"2")
L().Warnf("Hello, %s", name+"3")
Expand Down Expand Up @@ -255,10 +255,10 @@ func TestLoggerFile(t *testing.T) {
opts.DisableConsole = true
opts.DisableFile = false
opts.Output = tmp

Configure(opts, WithFilenameEncoder(func() string {
opts.FilenameEncoder = func() string {
return "test.log"
}))
}
Configure(opts)
Info("Hello, world!")
assert.Equal(t, filepath.Join(tmp, "test.log"), EncodedFilename())
_ = os.Remove(EncodedFilename())
Expand All @@ -268,7 +268,8 @@ func TestLoggerClose(t *testing.T) {
t.Run("close logger without log file", func(t *testing.T) {
str := "close logger without log file"
opts := NewOptions()
Configure(opts, WithTimeEncoder(DefaultTimeEncoder))
opts.TimeEncoder = DefaultTimeEncoder
Configure(opts)
defer func() {
if err := recover(); err != nil {
assert.Equal(t, err, str)
Expand Down
43 changes: 17 additions & 26 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,20 @@ type Logger struct {
closer io.Closer
log *zap.Logger
sugared *zap.SugaredLogger
filenameEncoder FilenameEncoder
timeEncoder TimeEncoder
levelEncoder LevelEncoder
callerEncoder CallerEncoder
encodedFilename string
}

// New creates a new Logger.
func New(opts *Options, encoders ...Encoder) *Logger {
func New(opts *Options) *Logger {
l := &Logger{}
if !opts.DisableFile && len(opts.Output) > 0 {
l.filenameEncoder = DefaultFilenameEncoder
// set a default filename encoder if log file is enabled
if !opts.DisableFile && len(opts.Output) > 0 && opts.FilenameEncoder == nil {
opts.FilenameEncoder = DefaultFilenameEncoder
}
l.withEncoders(encoders...)
var cores []zapcore.Core

encoderConfig := l.getEncoderConfig()
var cores []zapcore.Core
// set encoders, will override the default encoder if exists
encoderConfig := l.getEncoderConfig(opts)

if !opts.DisableConsole {
var consoleLevel Level
Expand All @@ -52,7 +49,8 @@ func New(opts *Options, encoders ...Encoder) *Logger {
if !opts.DisableConsoleCaller {
consoleEncCfg.CallerKey = "caller"
}
if !opts.DisableConsoleColor && l.levelEncoder == nil {
// forces to use CapitalColorLevelEncoder if LevelEncoder is not set when console color is enabled
if !opts.DisableConsoleColor && opts.LevelEncoder == nil {
consoleEncCfg.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
consoleLevelEnabler := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
Expand Down Expand Up @@ -93,7 +91,7 @@ func New(opts *Options, encoders ...Encoder) *Logger {
fileLevelEnabler := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= fileLevel
})
syncer, closer, encodedFilename = rollingFileEncoder(opts, l.filenameEncoder)
syncer, closer, encodedFilename = rollingFileEncoder(opts, opts.FilenameEncoder)
cores = append(cores, zapcore.NewCore(fileEncoder, syncer, fileLevelEnabler))
}
core := zapcore.NewTee(cores...)
Expand All @@ -111,13 +109,6 @@ func New(opts *Options, encoders ...Encoder) *Logger {
}
}

func (l *Logger) withEncoders(encoders ...Encoder) *Logger {
for _, encoder := range encoders {
encoder.apply(l)
}
return l
}

func (l *Logger) DebugLogger() DebugLogger {
return l
}
Expand Down Expand Up @@ -309,7 +300,7 @@ func (l *Logger) EncodedFilename() string {
return l.encodedFilename
}

func (l *Logger) getEncoderConfig() zapcore.EncoderConfig {
func (l *Logger) getEncoderConfig(opts *Options) zapcore.EncoderConfig {
encoderConfig := zapcore.EncoderConfig{
NameKey: "logger",
MessageKey: "msg",
Expand All @@ -320,14 +311,14 @@ func (l *Logger) getEncoderConfig() zapcore.EncoderConfig {
EncodeCaller: zapcore.ShortCallerEncoder,
ConsoleSeparator: " ",
}
if l.timeEncoder != nil {
encoderConfig.EncodeTime = l.timeEncoder
if opts.TimeEncoder != nil {
encoderConfig.EncodeTime = opts.TimeEncoder
}
if l.levelEncoder != nil {
encoderConfig.EncodeLevel = l.levelEncoder
if opts.LevelEncoder != nil {
encoderConfig.EncodeLevel = opts.LevelEncoder
}
if l.callerEncoder != nil {
encoderConfig.EncodeCaller = l.callerEncoder
if opts.CallerEncoder != nil {
encoderConfig.EncodeCaller = opts.CallerEncoder
}
return encoderConfig
}
9 changes: 9 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ type Options struct {

// Output directory for logging when DisableFile is false
Output string `json:"output" mapstructure:"output"`

// FilenameEncoder is used to set the log filename encoder.
FilenameEncoder FilenameEncoder `json:"-" mapstructure:"-"`
// TimeEncoder is used to set the log time encoder.
TimeEncoder TimeEncoder `json:"-" mapstructure:"-"`
// LevelEncoder is used to set the log level encoder.
LevelEncoder LevelEncoder `json:"-" mapstructure:"-"`
// CallerEncoder is used to set the log caller encoder.
CallerEncoder CallerEncoder `json:"-" mapstructure:"-"`
}

// NewOptions creates an Options with default parameters.
Expand Down
12 changes: 12 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,16 @@ func Test_Default_Options_Validate(t *testing.T) {
assert.Equal(t, "unrecognized level: \"errorlevel\"", errs[0].Error())
assert.Equal(t, "unrecognized level: \"errorlevel\"", errs[1].Error())
})

t.Run("options string", func(t *testing.T) {
opts := NewOptions()
opts.ConsoleLevel = "errorlevel"
opts.FileLevel = "errorlevel"
opts.FilenameEncoder = DefaultFilenameEncoder

output := opts.String()
assert.Contains(t, output, `"console-level":"errorlevel"`)
assert.Contains(t, output, `"file-level":"errorlevel"`)
assert.NotContains(t, output, "encoder")
})
}

0 comments on commit 6283da1

Please sign in to comment.