How to color logging output in Go

Better Stack Team
Updated on August 25, 2023

In Go, you can colorize logging output by using third-party libraries that support colored logging. One popular library for this purpose is "logrus," which provides a flexible logging framework with color support. Here's how you can use it to add colors to your logging output:

Install the logrus package using go get:

 
go get github.com/sirupsen/logrus

Import the logrus package in your Go code:

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

Set up the logrus logger:

 
func setupLogger() *logrus.Logger {
    logger := logrus.New()
    logger.SetFormatter(&logrus.TextFormatter{
        ForceColors: true, // Enable colors in the output
    })
    return logger
}

func main() {
    logger := setupLogger()

    // Now, you can use the logger to print colored output
    logger.WithFields(logrus.Fields{
        "animal": "walrus",
        "size":   10,
    }).Info("A group of walrus emerges from the ocean")
}

The ForceColors: true option in the TextFormatter ensures that the output is colored, regardless of the environment.

Keep in mind that the actual appearance of the colored output may vary depending on the terminal or console you are using to view the logs. Some terminals may not support colors or may need additional configuration.

If you want to use custom colors for different log levels or fields, logrus allows you to customize the color and appearance of the logs further. You can refer to the logrus documentation for more information: https://github.com/sirupsen/logrus

To learn more about logging in Go, visit Better Stack Community.

Got an article suggestion? Let us know
Explore more
Go
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →