rs / zerolog

Zero Allocation JSON Logger
MIT License
10.33k stars 564 forks source link

Add support to tagged Struct types #677

Open flejz opened 2 months ago

flejz commented 2 months ago

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