Home > Software engineering >  How can I log a struct automatically by zerolog?
How can I log a struct automatically by zerolog?

Time:01-23

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)

CodePudding user response:

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

  • Related