logutils — enhanced Go logging

logutils — enhanced Go logging

The standard Go log package is pretty barebones, but is fine for many simple programs. For more complex applications, though, you’d probably want to have different log levels for different events. There are many logging packages, such as the previously covered log15 that implement log leveling and provide other features. HashiCorp’s logutils is something different.

What logutils do

Here’s how authors describe it:

logutils is a Go package that augments the standard library “log” package to make logging a bit more modern, without fragmenting the Go ecosystem with new logging packages.

This means that instead of replacing the standard log package with another entirely different library, you’ll still use it for all your logging, but augment it by setting output filter, which provides powerful features.

How to use logutils

Install logutils with go get:

go get github.com/hashicorp/logutils

and then import it in addition to the standard log package:

import (
    "log"

    "github.com/hashicorp/logutils"
)

To do leveled logging, all you need is to create a filter with levels:

filter := &logutils.LevelFilter{
    Levels: []logutils.LogLevel{"DEBUG", "WARN", "ERROR"},
    MinLevel: "WARN",
    Writer: os.Stderr,
}

We created DEBUG, WARN, and ERROR levels and set the minimum level (which you’ll see in output) to WARN.

To make it work, set the standard logging package’s output to our filter:

log.SetOutput(filter)

And that’s it. Now, to assign levels to your log messages, simply begin them with a level name inside brackets:

log.Print("[DEBUG] Some debugging information")
log.Print("[WARN] This is a warning message")
log.Print("[ERROR] Oh noes, we've got an error!")
log.Print("This message doesn't use levels")

The first one, DEBUG won’t print because we set MinLevel to WARN. All other messages will be printed into the standard error:

2015/02/08 21:56:20 [WARN] This is a warning message
2015/02/08 21:56:20 [ERROR] Oh noes, we've got an error!
2015/02/08 21:56:20 This message doesn't use levels

As you can see, messages that were not updated to use levels still print.

I like logutils a lot! The package is easy to use and fulfills the promise of being “the simplest thing that could possibly work”.

Source code and license

GitHub: https://github.com/hashicorp/logutils

License: Mozilla Public License 2.0

Learn Go

Programming in Go: Creating Applications for the 21st Century

Leave a Reply

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