I am using zerolog for logging in a go application. I'd like to log a map (json) and find a way:
log.Info().
Str("foo", "bar").
Dict("dict", zerolog.Dict().
Str("bar", "baz").
Int("n", 1),
).Msg("hello world")
// Output: {"level":"info","time":1494567715,"foo":"bar","dict":{"bar":"baz","n":1},"message":"hello world"}
in above example, I need to specify each key-value pair in zerolog.Dict() method. I wonder whether there is an automatic way to log a struct.
For example, I have a struct like:
type Message struct {
AWS_REGION string `json:"region"`
LOG_LEVEL string `json:"level"`
STAGE string `json:"stage"`
REQUEST_ID string `json:"requestId"`
}
I am looking for a way to pass Message instance to
msg := Message{ ... }
zerolog.Dict("message", msg)
You can achieve this by using the Interface method.
Example
However, note that Interface uses reflection for serialisation, so code shortness comes at a cost of performance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With