zerolog icon indicating copy to clipboard operation
zerolog copied to clipboard

Add support to tagged Struct types

Open flejz opened this issue 1 week ago • 0 comments

One use case that me and my coworkers found is that we would often be loggin the same fields from a Struct over and over again, so we came up with the idea of logging tagged structs. That's what this PR is about.

That introduces a new concept of tagging the Struct with log followed by the log field name as the example below:


type User struct {
  Name   string `log:"name"`
  Active bool   `log:"is_active"`
}

Usage

We are introducing a new logging method Struct where you can pass the struct as an interface parameter.

user := User {
  Name:   "dude",
  Active: true,
}

log.Log().Struct(user).Msg("")

That would generate the log result as follows:

{"name":"dude","is_active":true}

PS: Ommiting the log tag will omit the struct field from the logs PS2: Nested struct fields are also supported

flejz avatar Jun 26 '24 16:06 flejz