feat(log): add hook option to log (#18916)

This commit is contained in:
Halimao 2023-12-30 19:22:45 +08:00 committed by GitHub
parent 4a2c13d445
commit c14ea022db
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 40 additions and 0 deletions

View File

@ -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

View File

@ -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}
}

View File

@ -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"))
}

View File

@ -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...)
}
}