diff --git a/log/CHANGELOG.md b/log/CHANGELOG.md index 21c93c7015..486a4016eb 100644 --- a/log/CHANGELOG.md +++ b/log/CHANGELOG.md @@ -22,6 +22,7 @@ Each entry must include the Github issue reference in the following format: ## [Unreleased] +* [#18916](https://github.com/cosmos/cosmos-sdk/pull/18916) Introduce an option for setting hooks. * [#18429](https://github.com/cosmos/cosmos-sdk/pull/18429) Support customization of log json marshal. ## [v1.2.1](https://github.com/cosmos/cosmos-sdk/releases/tag/log/v1.2.1) - 2023-08-25 diff --git a/log/logger.go b/log/logger.go index 64b985b90e..1d4cab1447 100644 --- a/log/logger.go +++ b/log/logger.go @@ -121,6 +121,11 @@ func NewLogger(dst io.Writer, options ...Option) Logger { logger = logger.Level(logCfg.Level) } + // TODO: when https://github.com/rs/zerolog/pull/629 is tagged, replace it to use logger.Hooks() + for i := range logCfg.Hooks { + logger = logger.Hook(logCfg.Hooks[i]) + } + return zeroLogWrapper{&logger} } diff --git a/log/logger_test.go b/log/logger_test.go index 95f3fb76f8..9c877a0ca4 100644 --- a/log/logger_test.go +++ b/log/logger_test.go @@ -7,6 +7,8 @@ import ( "testing" "cosmossdk.io/log" + "github.com/rs/zerolog" + "gotest.tools/v3/assert" ) func TestLoggerOptionStackTrace(t *testing.T) { @@ -30,3 +32,26 @@ func TestLoggerOptionStackTrace(t *testing.T) { func inner() error { return errors.New("seems we have an error here") } + +type _MockHook string + +func (h _MockHook) Run(e *zerolog.Event, l zerolog.Level, msg string) { + e.Bool(string(h), true) +} + +func TestLoggerOptionHooks(t *testing.T) { + buf := new(bytes.Buffer) + var ( + mockHook1 _MockHook = "mock_message1" + mockHook2 _MockHook = "mock_message2" + ) + logger := log.NewLogger(buf, log.HooksOption(mockHook1, mockHook2), log.ColorOption(false)) + logger.Info("hello world") + assert.Assert(t, strings.Contains(buf.String(), "mock_message1=true")) + assert.Assert(t, strings.Contains(buf.String(), "mock_message2=true")) + + buf.Reset() + logger = log.NewLogger(buf, log.HooksOption(), log.ColorOption(false)) + logger.Info("hello world") + assert.Assert(t, strings.Contains(buf.String(), "hello world")) +} diff --git a/log/options.go b/log/options.go index 22a1eb2284..28cfefee2e 100644 --- a/log/options.go +++ b/log/options.go @@ -14,6 +14,7 @@ var defaultConfig = Config{ Color: true, StackTrace: false, TimeFormat: time.Kitchen, + Hooks: nil, } // Config defines configuration for the logger. @@ -24,6 +25,7 @@ type Config struct { Color bool StackTrace bool TimeFormat string + Hooks []zerolog.Hook } type Option func(*Config) @@ -87,3 +89,10 @@ func TraceOption(val bool) Option { cfg.StackTrace = val } } + +// HooksOption append hooks to the Logger hooks +func HooksOption(hooks ...zerolog.Hook) Option { + return func(cfg *Config) { + cfg.Hooks = append(cfg.Hooks, hooks...) + } +}