Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log a struct automatically by zerolog?

Tags:

logging

go

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)
like image 601
Joey Yi Zhao Avatar asked Oct 28 '25 01:10

Joey Yi Zhao


1 Answers

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

like image 188
Igor Morozov Avatar answered Oct 31 '25 08:10

Igor Morozov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!