Elevate Your Golang Logging with the Strength of Logrus

Taking a Deeper Dive into Efficient Logging Practices in Golang

Mehran
ITNEXT

--

Generated using Lexica

Introduction

Hello there, code lovers! If you’re anything like me, then you know that logging is a critical part of the software development process. That unsung hero gives us insight into how our application runs, acting as our eyes and ears into the intricate workings of our code. Today, I’ll introduce you to a fantastic logging library for Go — Logrus.

The Beauty of Logrus

Now, let’s move to the star of today’s post — Logrus. Logrus is a structured logger for Golang, completely API-compatible with the standard library logger. It’s packed with nifty features like:

  • Full compatibility with the standard library’s logger API.
  • Log level severity allows control over what gets logged.
  • Log formatting, supporting both text and JSON, with the ability to create custom formatters.
  • Hooks for logging levels, perfect for integrating with logging systems like Logstash.

So, without further ado, let’s dive into the fun part — examples! We’ll look at twelve different uses of Logrus: basic logging, formatting logs, implementing hooks, etc.

Example 1: Basic Logging with Logrus

First things first, we need to install Logrus. Run the following command:

go get github.com/sirupsen/logrus

Now, let’s log a simple error message:

package main

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

func main() {
logrus.Error("Something went wrong!")
}

When you run this program, you’ll see “ERRO[0000] Something went wrong!” printed in your console. ‘ERRO’ is the error level, and ‘[0000]’ is the timestamp.

Example 2: Formatting Logs with Logrus

One of the beautiful things about Logrus is its ability to format logs. Let’s say you want your logs in JSON format instead of the default text format:

package main

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

func main() {
logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.Info("This is an informational message.")
}

Here, we’re setting the log format to JSON and logging an informational message. When you run this, you’ll get a JSON-formatted log entry like this: {"level":"info","msg":"This is an informational message.","time":"2023-07-23T14:56:00Z"}.

Example 3: Implementing Hooks with Logrus

Logrus hooks can be extremely useful for sending log entries to external services that Logrus don’t already support. Here’s an example of a hook that logs all warnings and above to a hypothetical bug tracker:

package main

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

type BugTrackerHook struct{}

func (hook *BugTrackerHook) Levels() []logrus.Level {
return []logrus.Level{
logrus.WarnLevel,
logrus.ErrorLevel,
logrus.FatalLevel,
logrus.PanicLevel,
}
}

func (hook *BugTrackerHook) Fire(entry *logrus.Entry) error {
// Log the entry to your bug tracker here
return nil
}

func main() {
logrus.AddHook(&BugTrackerHook{})
logrus.Warn("This is a warning message.")
}

In this example, we first define a struct BugTrackerHook implementing Levels() method to indicate which levels this hook should be fired for and Fire() method to act with a log entry. Then we add this hook to Logrus using. AddHook() The method and create a warning log. If you have a bug tracker service, you can add code to send the log entry to it within Fire() method.

Example 4: Setting the Log Level

Logrus provides several log levels. You can set the log level to control the severity of the logs that will be written.

package main

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

func main() {
logrus.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
}

Example 6: Logging a Fatal Error

If you have a severe error that needs to terminate the program, you can use Fatal which logs the error and calls os.Exit(1).

package main

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

func main() {
logrus.Fatal("This is a fatal error!")
}

Example 7: Logging With a Panic

In case you need to log an error message and panic, use Panic.

package main

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

func main() {
logrus.Panic("This is a panic log!")
}

Example 8: Using The Trace Level

If you want even more detail than Debug, Logrus provides a Trace level.

package main

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

func main() {
logrus.SetLevel(logrus.TraceLevel)
logrus.Trace("This is a trace log.")
}

Example 9: Logging to an io.Writer

Logrus can also write its output to any. io.Writer.

package main

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

func main() {
logrus.SetOutput(os.Stdout)
logrus.Info("This log is written to stdout.")
}

Example 10: Logging in Different Timezones

You can set your preferred timezone for the log timestamps.

package main

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

func main() {
// Use UTC time
logrus.SetFormatter(&logrus.JSONFormatter{TimestampFormat: time.RFC3339})

logrus.Info("Log with RFC3339 timestamp format.")
}

Example 11: Log Entry Order

You can maintain a consistent order of log entry fields.

package main

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

func main() {
logrus.SetFormatter(&logrus.JSONFormatter{FieldMap: logrus.FieldMap{
logrus.FieldKeyTime: "@timestamp",
logrus.FieldKeyLevel: "@level",
logrus.FieldKeyMsg: "@message",
}})
logrus.Info("Log with consistent field order.")
}

Example 12: Custom Log Formatter

You can create custom formatters to control how log entries are formatted.

package main

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

type CustomFormatter struct{}

func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) {
return []byte(fmt.Sprintf("%s: %s\n", entry.Level.String(), entry.Message)), nil
}

func main() {
logrus.SetFormatter(new(CustomFormatter))
logrus.Info("Log with a custom formatter.")
}

Wrap Up

Logrus is a fantastic library that adds robust, flexible logging to your Golang applications. Whether you’re working on a small side project or an enterprise-level application, Logrus can fit in seamlessly and provide the level of logging detail you need.

From a simple print to console to sophisticated hooks triggering actions on specific log levels, Logrus offers unparalleled flexibility in Go logging.

So, try Logrus, and let me know how it goes. Until next time, happy coding, folks!

--

--

Writer for

Tech Team Lead | Cloud, Video & Microservices Expert | Insights on streaming innovations & programming. #ContinuousLearning