diff --git a/log/logger.go b/log/logger.go index bb0896eea541..6697c805af6d 100644 --- a/log/logger.go +++ b/log/logger.go @@ -1,7 +1,6 @@ package log import ( - "encoding" "encoding/json" "fmt" "io" @@ -11,6 +10,17 @@ import ( "github.com/rs/zerolog/pkgerrors" ) +func init() { + zerolog.InterfaceMarshalFunc = func(i interface{}) ([]byte, error) { + switch v := i.(type) { + case fmt.Stringer: + return json.Marshal(v.String()) + default: + return json.Marshal(i) + } + } +} + // ModuleKey defines a module logging key. const ModuleKey = "module" @@ -42,6 +52,18 @@ type Logger interface { Impl() any } +// WithJSONMarshal configure zerolog global json encoding +func WithJSONMarshal(marshaler func(v any) ([]byte, error)) { + zerolog.InterfaceMarshalFunc = func(i interface{}) ([]byte, error) { + switch v := i.(type) { + case fmt.Stringer: + return marshaler(v.String()) + default: + return marshaler(i) + } + } +} + type zeroLogWrapper struct { *zerolog.Logger } @@ -59,21 +81,6 @@ func NewLogger(dst io.Writer, options ...Option) Logger { for _, opt := range options { opt(&logCfg) } - // set default jsonMarshaler to json.Marshal for compatibility - jsonMarshaler := json.Marshal - if logCfg.JSONMarshal != nil { - jsonMarshaler = logCfg.JSONMarshal - } - zerolog.InterfaceMarshalFunc = func(i interface{}) ([]byte, error) { - switch v := i.(type) { - case json.Marshaler, encoding.TextMarshaler: - return jsonMarshaler(i) - case fmt.Stringer: - return jsonMarshaler(v.String()) - default: - return jsonMarshaler(i) - } - } output := dst if !logCfg.OutputJSON { diff --git a/log/options.go b/log/options.go index e2a55679a096..22a1eb22841f 100644 --- a/log/options.go +++ b/log/options.go @@ -1,7 +1,6 @@ package log import ( - "encoding/json" "time" "github.com/rs/zerolog" @@ -9,24 +8,22 @@ import ( // defaultConfig has all the options disabled, except Color and TimeFormat var defaultConfig = Config{ - Level: zerolog.NoLevel, - Filter: nil, - OutputJSON: false, - Color: true, - StackTrace: false, - TimeFormat: time.Kitchen, - JSONMarshal: json.Marshal, + Level: zerolog.NoLevel, + Filter: nil, + OutputJSON: false, + Color: true, + StackTrace: false, + TimeFormat: time.Kitchen, } // Config defines configuration for the logger. type Config struct { - Level zerolog.Level - Filter FilterFunc - OutputJSON bool - Color bool - StackTrace bool - TimeFormat string - JSONMarshal func(v any) ([]byte, error) + Level zerolog.Level + Filter FilterFunc + OutputJSON bool + Color bool + StackTrace bool + TimeFormat string } type Option func(*Config) @@ -90,10 +87,3 @@ func TraceOption(val bool) Option { cfg.StackTrace = val } } - -// JSONMarshalOption add option to configure custom JSON encoding -func JSONMarshalOption(f func(v any) ([]byte, error)) Option { - return func(cfg *Config) { - cfg.JSONMarshal = f - } -}