Golang — Structured logging using zap
I know so many articles exist out there on how to do structured logging with zap in Go but well none of them met my simplicity standards. So I just wanted to show you how to set up a basic zap configuration and get going with structured logging in your Go application.
Zap provides blazingly fast, simple, structured logging in go. Zap is more performant than comparable structured logging packages as can be seen from the below snapshot from the results of one of Zap’s own benchmarking suite.
The next obvious question that comes in mind is when to use zap (Logger) vs zap (SugaredLogger)?
Logger supports only structured logging where as SugaredLogger includes both structured and printf
-style APIs though that comes at a performance cost as is evident from the performance results above. So in contexts where performance is nice, but not critical, use the SugaredLogger as it provides a formatting method for additional parameters and provides greater convenience to format specific messages.
Configuration-
I always like to wrap my logger configuration in a separate function. This helps you initialize the logger easily in your tests. This logger configuration will define how Zap is going to print the information received. There are many options available to configure the zap logger. I’m just going to show a basic configuration that should meet your needs most of the time.
The NewProductionConfig function returns an opinionated EncoderConfig for production environments, which have several fields already configured. We are going to change only two, “EncodeTime” and EncodeLevel. The later prints the log level in all capital . ISO8601TimeEncoder serializes a time to an ISO8601-formatted string// with millisecond precision.
LoggingLevel-
There are 7 levels of priority, these being:
Usage-
The usage in your application is pretty simple. As mentioned above, SugaredLogger allows you to do both structured logging and printf style logging. You can use the following variants to suit your logging needs.
Before we wrap this, you might have a situation where you decide to use both Logger and SugaredLogger. In that case you can always return an instance of *zap.Logger from your Initilogger like:
and use both Logger and SugaredLogger like:
This post is a continuation to my first Medium post https://harshnanchahal.medium.com/error-handling-in-golang-made-easy-7a135abed906
Any feedback it’s welcome! Have a great day y’all :)