zerolog Objects

Wed, May 25, 2022 One-minute read

zerolog Objects

zerolog is so good. Today I learnt that it can use marshal structs into an object for logging. All you need to do is add the MarshalZerologObject method to the struct. Then it will be accessible on the logger via the .Object method.

Example.

// user.go
type User struct {
  Name  string `json:"name"`
  Email string `json:"email"`
}

func (u User) MarshalZerologObject(e *zerolog.Event) {
  e.Str("user", u.Name).Str("email", u.Email)
}

// where its called
u := User{Name: "test", Email: "test@test.com"}
logger.Info().Object("user", u).Msg("user logged")
// outputs:
//    INF user logged user={"name":"test","email":"test@test.com"}

Note the above example output is using a ConsoleLogger, not the JSONLogger which you should use in production.

Tags:

#go #zerolog