A Handy Generic Logging FieldBuilder Template around uber-go/zap. You can check this tiny blog for further information 🙂
Anybody who likes to code in Go, also uses Structured Logging with uber-go/zap and (most importantly) loves cleaner and neater code.
Instead of having lots of logging lines repeatedly along the codebase such as the following
logger.Debug("Firing Event",
zap.Int("event-id", id),
zap.String("event-type", "TakeOff"),
zap.String("issuer", user.getName()),
zap.Int("account-id", user.getAccountId()),
zap.Time("timestamp", time.Now().Format(time.RFC3339)))
... having those fields built flexibly and reusable like this
fields := logger.FieldBuilder().
EventId(id).
EventType("TakeOff").
Issuer(user.getName()).
AccountId(user.getAccountId()).
Timestamp(time.Now().Format(time.RFC3339))
/* ... */
if /* ... */ {
log.Debug("Firing Event...", fields.AnotherField(fieldPayload).Build()...)
} else {
log.Debug("Firing Event...", fields.Build()...)
}
- Clone this template repository
git clone https://github.com/ysyesilyurt/zap-fieldbuilder-template.git
-
Using the
logger/field_builder.goadopt this FieldBuilder template to your codebase. -
Simply add all your
Buildermethods that you are going to use in your logging statement aszap.Fieldwhen needed as needed. You can use the follwingZapFieldBuildermethod body pattern.
func (zfb *ZapFieldBuilder) Status(status int) *ZapFieldBuilder {
return zfb.addOrReplaceField(zap.Int(LogFieldStatus, status))
}
-
Initialize your FieldBuilder using the constructor
FieldBuilder()and just start building yourzap.Fields with your builder methods. -
Now you can log them to anywhere using
Build()method which would yield you the underlying[]zap.Field.