Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(log): support customization of log json marshal #18429

Merged
merged 13 commits into from
Nov 12, 2023
2 changes: 2 additions & 0 deletions log/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)).
Expand Down
17 changes: 12 additions & 5 deletions log/logger.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package log

import (
"encoding"
"encoding/json"
"fmt"
"io"
Expand All @@ -14,10 +13,6 @@ import (
func init() {
zerolog.InterfaceMarshalFunc = func(i interface{}) ([]byte, error) {
switch v := i.(type) {
case json.Marshaler:
lilasxie marked this conversation as resolved.
Show resolved Hide resolved
return json.Marshal(i)
case encoding.TextMarshaler:
return json.Marshal(i)
case fmt.Stringer:
return json.Marshal(v.String())
default:
lilasxie marked this conversation as resolved.
Show resolved Hide resolved
Expand Down Expand Up @@ -57,6 +52,18 @@ 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 fmt.Stringer:
lilasxie marked this conversation as resolved.
Show resolved Hide resolved
lilasxie marked this conversation as resolved.
Show resolved Hide resolved
return marshaler(v.String())
default:
return marshaler(i)
}
}
}

type zeroLogWrapper struct {
*zerolog.Logger
}
Expand Down