From b494d6a23edc17c877a895743bebda1d48bffbcc Mon Sep 17 00:00:00 2001 From: lilas <30857671+lilasxie@users.noreply.github.com> Date: Sun, 12 Nov 2023 21:28:09 +0800 Subject: [PATCH] feat(log): support customization of log json marshal (#18429) Co-authored-by: Julien Robert Co-authored-by: Aleksandr Bezobchuk --- log/CHANGELOG.md | 2 ++ log/logger.go | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/log/CHANGELOG.md b/log/CHANGELOG.md index 8faf08db32..21c93c7015 100644 --- a/log/CHANGELOG.md +++ b/log/CHANGELOG.md @@ -22,6 +22,8 @@ Each entry must include the Github issue reference in the following format: ## [Unreleased] +* [#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 * [#17532](https://github.com/cosmos/cosmos-sdk/pull/17532) Proper marshalling of `fmt.Stringer` (follow-up of [#17205](https://github.com/cosmos/cosmos-sdk/pull/17205)). diff --git a/log/logger.go b/log/logger.go index 859212db27..64b985b90e 100644 --- a/log/logger.go +++ b/log/logger.go @@ -12,7 +12,7 @@ import ( ) func init() { - zerolog.InterfaceMarshalFunc = func(i interface{}) ([]byte, error) { + zerolog.InterfaceMarshalFunc = func(i any) ([]byte, error) { switch v := i.(type) { case json.Marshaler: return json.Marshal(i) @@ -57,6 +57,22 @@ type Logger interface { Impl() any } +// WithJSONMarshal configures zerolog global json encoding. +func WithJSONMarshal(marshaler func(v any) ([]byte, error)) { + zerolog.InterfaceMarshalFunc = func(i any) ([]byte, error) { + switch v := i.(type) { + case json.Marshaler: + return marshaler(i) + case encoding.TextMarshaler: + return marshaler(i) + case fmt.Stringer: + return marshaler(v.String()) + default: + return marshaler(i) + } + } +} + type zeroLogWrapper struct { *zerolog.Logger }