Craft

4 Efficient Logging Packages for Your Go Apps

Logging is the technique of keeping records for future purposes in the software development cycle. Logging is critical because logs help with debugging, diagnostics, troubleshooting, and project monitoring.

You can use logging at various levels of your applications for errors, warnings, debugging, and more.

Logging in Go

The Go standard library contains a log package rich in functionality. It handles various logging levels and basic logging-related methods you’ll need for your application. However, the log package might not be the best choice if your app is complex and you want to prioritize productivity.

The log package doesn’t provide functionality for structured logs. Structured logging packages provide functionality that simplifies and improves the logging process. The Go ecosystem is home to many such packages.

1. Zap by Uber

Zap is a fast, structured, leveled logging package built by Uber’s open-source team for writing logs in Go. Uber built the Zap package to provide more performant logging than other packages in the Go ecosystem, including the log package.


There are two distinct loggers in the Zap package. The Logger function handles critical performance cases. The SugaredLogger offers more flexibility with its printf-style API, but it comes with a small tradeoff in performance. Even the slower SugaredLogger package is 4-10 times faster than other structured logging packages.

Run the following on a command line to install the Zap package:

go get -u go.uber.org/zap

You’ll need a recent version of Go to install and use the Zap package’s functionality successfully.

logger, err := zap.NewProduction() 

if err != nil {
fmt.Println(err.Error())
}

defer logger.Sync()
sugar := logger.Sugar()

sugar.Infow("failed to fetch URL",
"url", url,
"attempt", 3,
"backoff", time.Second,
)

sugar.Infof("Failed to fetch URL: %s", URL)

The logger variable is an instance of the zap logger, and the Sugar method is a sugared logger instance.

The Infow method writes to the output, and the Infof is the formatting version of the Infow method.

2. The Logrus Package

Logrus is a structured logging package for Go apps. Logrus is compatible with the standard library logger, with similar functionality. If you have experience using the log package, you’ll find a suite working with Logrus.

Logrus doesn’t support JSON formatting by default. But you can always use a JSON library like the built-in json package with Logrus’ SetFormatter method.

Logrus supports logging at different levels and, although it’s not as performant as most logging packages, it’s feature-rich and safe.

You can use this command to install Logrus in your working directory:

go get github.com/sirupsen/logrus

Here’s an example of logging with the Logrus package.

import (
"os"
log "github.com/sirupsen/logrus"
)

func main {
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
log.SetLevel(log.WarnLevel)

log.WithFields(log.Fields{
"Name": "John Doe",
"Age": 40,
}).Info("John's Bio Data")
}

This code imports the Logrus library and creates an alias for it named log. In the main function, it calls the SetFormatter method to set a formatter for the logs. You can use the SetOutput method to specify where log messages should go; in this case, standard output.


The SetLevel method logs warnings in the specified level or above.

3. ZeroLog Package

ZeroLog is a Zap-inspired, fast, JSON-dedicated library for logging, designed for performance. It uses a unique chaining API that allows Zerolog to write JSON and log events without allocations and reflections.

Zerolog aims to provide an easier-to-use API and higher performance while keeping the code base and API simple. It focuses on structured logging and you can use the ConsoleWriter method for pretty logging on your console.

There’s low allocation, leveled logging, sampling, hooks, contextual fields, and error logging with optional stack trace features on the Zerolog package. You can also integrate Zerolog with the context and http packages.

Run this command in the terminal of your workspace to install the Zerolog package.

go get -u [github.com/rs/zerolog/log](http:

Here’s a simple example of using the Zerolog package for a simple operation.

import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

log.Print("hello world")
}

The TimeFieldFormat option is set to the Unix time format, and the Print command writes the text argument to standard output.

4. The Log15 Package

The Log15 package is a simple opinionated toolkit for human and machine-readable logging with best practices in Go. Log15 models the io and http packages from the Go standard library as an alternative to the built-in log package.


The features of the Log15 package include:

  • a simple, easy-to-understand API
  • structured logging with key-value pairs
  • child loggers with private context
  • handler interface for constructing custom logging configurations over a tiny API
  • colored terminal support
  • built-in support for logging to files, streams, system logs, and network logs
  • buffering records to output.

You can install Log15 to your Go packages with this command.

go get github.com/inconshreveable/log15

It’s easy to get started with the Log15 package. Here’s an example of instantiating a logger and logging on info and error levels with the package.

import (
log "github.com/inconshreveable/log15"
)

func main() {
serverLog := log.New("repository", "new repository")
serverLog.Info("repository layer health check successful")
serverLog.Error("repository layer health check failed")
}

The serverLog variable is an instance of the Log15 logger; the New method returns a logger with the context arguments you provide.

The Info method returns an info message, and the Error method returns an error message.

Write Useful and Understandable Logs

Logging can be as critical as any other part of the development process. It may seem very easy in the initial stages, but sticking to essential practices may complicate the process. To handle every edge-case and aspect of logging, you should use a logging package to make things easier.

Use logging levels, structure, and context to make your logs understandable and fit for their intended purposes.

[quads id=2]
Read the full article here

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button