Skip to content

Structured fields

Michael Kenney edited this page Jan 23, 2019 · 2 revisions

bdlm/log encourages careful, structured logging through logging fields instead of long, unparseable error messages. For example, instead of: log.Fatalf("Failed to send event %s to topic %s with key %d"), you should log the much more discoverable:

log.WithFields(log.Fields{
    "event": event,
    "topic": topic,
    "key": key,
}).Fatal("Failed to send event")

This API forces you to think about logging in a way that produces much more useful logging messages. We've been in countless situations where just a single added field to a log statement that was already there would've saved us hours. The WithFields call is optional.

In general, with bdlm/log using any of the printf-family functions should be seen as a hint you should add a field, however, you can still use the printf-family functions with bdlm/log.

Default Fields

Often it's helpful to have fields always attached to log statements in an application or parts of one. For example, you may want to always log the request_id and user_ip in the context of a request. Instead of writing log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) on every line, you can create a log.Entry to pass around instead:

requestLogger := log.WithFields(log.Fields{
	"request_id": request_id,
	"user_ip": user_ip
})

// will log request_id and user_ip
requestLogger.Info("something happened on that request")
requestLogger.Warn("something not great happened")

Clone this wiki locally