Skip to content

Commit

Permalink
update to use file or stderr output
Browse files Browse the repository at this point in the history
  • Loading branch information
belimawr committed Jan 22, 2024
1 parent 5cacb6c commit efb1175
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
24 changes: 18 additions & 6 deletions logp/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,13 +236,25 @@ func makeEventLogOutput(cfg Config, enab zapcore.LevelEnabler) (zapcore.Core, er
return wrappedCore(core), nil
}

// WithFileOutput creates a new file output based on cfg and
// replaces the previous one.
func WithFileOutput(cfg Config) func(zapcore.Core) zapcore.Core {
out, err := makeFileOutput(cfg, cfg.Level.ZapLevel())
if err != nil {
L().Errorf("could not create file output: %s", err)
// WithFileOrStderrOutput configures the logger with an output based on cfg.
// If neither `cfg.ToFiles` nor `cfg.ToSdterr` are true, then a noop output
// is created. If both are true, the file output has preference.
func WithFileOrStderrOutput(cfg Config) func(zapcore.Core) zapcore.Core {
var out zapcore.Core
var err error

switch {
case cfg.ToFiles:
out, err = makeFileOutput(cfg, cfg.Level.ZapLevel())
case cfg.ToStderr:
out, err = makeStderrOutput(cfg, cfg.Level.ZapLevel())
default:
out = zapcore.NewNopCore()
err = errors.New("unexpected output type, only allowed outputs are 'file' and 'stderr'")
}

if err != nil {
L().Errorf("could not create log output: %s", err)
}

f := func(zapcore.Core) zapcore.Core {
Expand Down
2 changes: 1 addition & 1 deletion logp/core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ func TestWithFileOutput(t *testing.T) {
// We do not call Configure here as we do not want to affect
// the global logger configuration
secondLogger := NewLogger(t.Name() + "-second")
secondLogger = secondLogger.WithOptions(zap.WrapCore(WithFileOutput(secondCfg)))
secondLogger = secondLogger.WithOptions(zap.WrapCore(WithFileOrStderrOutput(secondCfg)))
secondLogger.Info(expectedLogMessage)
if err := secondLogger.Sync(); err != nil {
t.Fatalf("could not sync log file from second logger: %s", err)
Expand Down

0 comments on commit efb1175

Please sign in to comment.