-
Notifications
You must be signed in to change notification settings - Fork 1.4k
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: Custom interface{}
object Encoder
#1034
Comments
Hey, @psrajat. This is a reasonable feature request, although I would suggest some small changes to it: So maybe something like this: type ReflectedEncoder interface { Encode(interface{}) error }
// json.Encoder and jsoniter.Encoder both match this interface.
type EncoderConfig struct {
// ...
NewReflectedEncoder func(io.Writer) ReflectedEncoder
} Zap would still own the buffer and reset it as needed. |
This adds support for overriding the mechanism we use to encode `ReflectType` fields. That is, in the following, log.Info("foo", zap.Reflect("bar", baz)) It allows `baz` to be serialized using a third-party JSON library by providing a custom ReflectedEncoder in the zapcore.EncoderConfig. `encoding/json`'s Encoder type is a valid ReflectedEncoder. Resolves #1034 Co-authored-by: Sung Yoon Whang <sungyoonwhang@gmail.com> Co-authored-by: Abhinav Gupta <abg@uber.com>
Thanks, @psrajat! We'll tag a new release of Zap in January. |
Thanks a lot for helping out @abhinav :) |
Description
We log a lot of structs using zap. And zap uses
json.Encoder
for encoding theseinterface{}
(orReflectType
) fields.It would be great if we can use something else other than
encoding/json
lib.For instance, json-iterator is faster than std lib and provides other customizations on top of it.
This would provide 2 benefits:
interface{}
objects in a custom way.For example: json-iterator provides the functionality to have custom tags instead of
json
.With this feature, we can control what we want to log.
In the above example, we want to only log
Name
andAge
but don't want to logEmail
andAddress
.Since this is using its own instance, it won't affect other serializations/deserializations taking place somewhere else.
On Implementation
I figured one way we can do this is by replacing the type of
reflectEnc
variable to a newly definedReflectTypeEncoder
interface injson_encoder.go
.This interface will expose mainly 2 methods:
WithBuffer(*buffer.Buffer)
: which will provide the encoder the Buffer where it needs to write the dataEncode(interface{})
: which encodes the object and writes it to the provided buffer aboveThe configuration can be provided while initializing
Logger
:If not provided, we can continue using the default
encoding/json
one so won't be a breaking change.LMK if there are any concerns with this approach.
Or there are other ways I can do this.
If you're okay with it, I can raise a PR.
Note: This may also solve #993
The text was updated successfully, but these errors were encountered: