From 0b7d2d310b5a43128db44639b7d8022d6cee37ee Mon Sep 17 00:00:00 2001 From: zakir <80246097+zakir-code@users.noreply.github.com> Date: Mon, 31 Jul 2023 18:33:15 +0800 Subject: [PATCH] fix(log): add fallback to `Stringer` when type do not implement `json.Marshaler` interface (#17205) --- log/CHANGELOG.md | 4 ++++ log/logger.go | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/log/CHANGELOG.md b/log/CHANGELOG.md index 80a98e2fd61c..439523bdba5f 100644 --- a/log/CHANGELOG.md +++ b/log/CHANGELOG.md @@ -37,6 +37,10 @@ Ref: https://keepachangelog.com/en/1.0.0/ * [#17194](https://github.com/cosmos/cosmos-sdk/pull/17194) Avoid repeating parse log level in filterFunc. +### Bug Fixes + +* [#17205](https://github.com/cosmos/cosmos-sdk/pull/17205) Fix types that do not implement the `json.Marshaler` interface. + ## [v1.1.0](https://github.com/cosmos/cosmos-sdk/releases/tag/log/v1.1.0) - 2023-04-27 * [#15956](https://github.com/cosmos/cosmos-sdk/pull/15956) Introduce options to configure logger (enable/disable colored output, customize log timestamps). diff --git a/log/logger.go b/log/logger.go index c6a86e18ba9a..0d1dd60a5d0a 100644 --- a/log/logger.go +++ b/log/logger.go @@ -1,6 +1,9 @@ package log import ( + "encoding" + "encoding/json" + "fmt" "io" "github.com/pkg/errors" @@ -8,6 +11,21 @@ import ( "github.com/rs/zerolog/pkgerrors" ) +func init() { + zerolog.InterfaceMarshalFunc = func(i interface{}) ([]byte, error) { + switch v := i.(type) { + case json.Marshaler: + return json.Marshal(i) + case encoding.TextMarshaler: + return json.Marshal(i) + case fmt.Stringer: + return fmt.Appendf([]byte("\""), "%s%s", v.String(), "\""), nil + default: + return json.Marshal(i) + } + } +} + // ModuleKey defines a module logging key. const ModuleKey = "module"