Simple Go logging using Logrus.

I've been looking for a feature complete logging package for Go this weekend.

I found Logrus and it's really easy to set up and powerful.


First, let's import the package to our sample application.

package main

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

func main() {  
}
  • run go get in your terminal.

To log information, create a new logrus object and call it's various functions.

package main

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

var log = logrus.New()

func main() {  
    log.Debug("Useful debugging information.")
    log.Info("Something noteworthy happened!")
    log.Warn("You should probably take a look at this.")
    log.Error("Something failed but I'm not quitting.")
    // Calls os.Exit(1) after logging
    log.Fatal("Bye.")
    // Calls panic() after logging
    log.Panic("I'm bailing.")
}

By default Logrus will output log information to the stdout - so you'll see some info pop up in your terminal when you run this.


Where I think Logrus really shines though, is with it's pretty printing and clean way to attach arbitrary fields.

For example, say we want to log some additional data along with the string message.

package main

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

var log = logrus.New()

func main() {  
    log.WithFields(logrus.Fields{
        "first_name": "sergio",
        "last_name": "tapia",
    }).Info("User account created successfully.")
}

Output:

INFO[0000] User account created successfully.      first_name=sergio last_name=tapia  

If you need the info in JSON format, you can easily change the formatter.

log.Formatter = new(logrus.JSONFormatter)  

Output:

{"first_name":"sergio","last_name":"tapia","level":"info","msg":"User account created successfully.","time":"2014-07-18 22:35:12.645345431 -0400 BOT"}

You can also make Logrus only output logs above a certain threshold of severity.

For example, let's only show logs that are Warn or higher.

package main

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

var log = logrus.New()

func main() {  
    log.Level = logrus.Warn

    log.WithFields(logrus.Fields{
        "first_name": "sergio",
        "last_name":  "tapia",
    }).Info("User account created successfully.")

    log.WithFields(logrus.Fields{
        "first_name": "sergio",
        "last_name":  "tapia",
    }).Warn("Multiple user account attempts.")

        log.WithFields(logrus.Fields{
        "first_name": "sergio",
        "last_name":  "tapia",
    }).Fatal("User permission attribute modified.")
}

Output:

WARN[0000] Multiple user account attempts.               first_name=sergio last_name=tapia  
FATA[0000] User permission attribute modified.           first_name=sergio last_name=tapia  

And there you go, one of the easiest logging libraries I've ever used.

You can find the public repository for Logrus here:

https://github.com/Sirupsen/logrus

comments powered by Disqus