From fc0e129602d97662577f94e70cf3c2c47287d124 Mon Sep 17 00:00:00 2001 From: Tiago Queiroz Date: Tue, 19 Dec 2023 12:14:42 +0100 Subject: [PATCH] [logp] Allow a logger to change its output This commit enables a logger to change its output after creation and independently from the global logger configuration. --- logp/configure/logging.go | 4 ++++ logp/core.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/logp/configure/logging.go b/logp/configure/logging.go index f23e1792..06d006a0 100644 --- a/logp/configure/logging.go +++ b/logp/configure/logging.go @@ -45,6 +45,10 @@ func init() { flag.Var((*environmentVar)(&environment), "environment", "set environment being ran in") } +func GetEnvironment() logp.Environment { + return environment +} + // Logging builds a logp.Config based on the given common.Config and the specified // CLI flags. func Logging(beatName string, cfg *config.C) error { diff --git a/logp/core.go b/logp/core.go index 321a20d4..cb6b7e7d 100644 --- a/logp/core.go +++ b/logp/core.go @@ -236,6 +236,22 @@ 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, zap.DebugLevel) + if err != nil { + L().Errorf("could not create file output: %s", err) + out = zapcore.NewNopCore() + } + + f := func(zapcore.Core) zapcore.Core { + return out + } + + return f +} + func makeFileOutput(cfg Config, enab zapcore.LevelEnabler) (zapcore.Core, error) { filename := paths.Resolve(paths.Logs, filepath.Join(cfg.Files.Path, cfg.LogFilename()))