DEV Community

Cover image for Simplify Logging in Go Applications Configuration Logrus
Suharxxxx
Suharxxxx

Posted on • Updated on

Simplify Logging in Go Applications Configuration Logrus

Logrus

is a structured logger for Go (golang), completely API compatible with the standard library logger, popular logging library that provides extensive features and flexibility for logging in Go applications. logrus

First, we import the log package from logrus, which is the official Logrus package. Logrus is a popular logging library for Go that provides powerful features and flexibility.

package main

import (
  // "os"
  log "github.com/sirupsen/logrus"
)
Enter fullscreen mode Exit fullscreen mode

In the code snippet, the log package is aliased as log from the logrus package. This allows you to use the Logrus library under the log namespace.

Example

The easiest approach to utilize Logrus is by utilizing the logger exported at the package level.

package main

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

func main() {

  log.WithFields(log.Fields{
    "animal": "walrus",
  }).Info("A walrus appears")

}
Enter fullscreen mode Exit fullscreen mode

The code snippet above demonstrates the usage of Logrus, a logging library in Go. In the function, we use the method to attach additional information to a log entry before printing it WithFields()

In this example, we create a log entry with the field set to . This field represents the type of animal that appears in the log entry.animal : walrus

Image description

Certainly! Here's a simplified explanation of the different error levels in Logrus :

  • Error: Used for critical errors in the application.
  • Warn: Used for non-critical warnings that require attention.
  • Info: Used for informative messages to track important events.
  • Debug: Used for debugging purposes during development.
  • Fatal: Used for fatal errors that cause the application to stop abruptly.
package main

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

func main() {
  log.WithFields(log.Fields{
    "animal": "cat",
  }).Error("A walrus appears")

  log.WithFields(log.Fields{
    "animal": "fish",
  }).Debug("A walrus appears")

  log.WithFields(log.Fields{
    "animal": "walrus",
  }).Info("A walrus appears")

  log.WithFields(log.Fields{
    "animal": "dog",
  }).Warn("A walrus appears")

  log.WithFields(log.Fields{
    "animal": "pig",
  }).Fatal("A walrus appears")
}
Enter fullscreen mode Exit fullscreen mode

Image description

func init() {
  // Log as JSON instead of the default ASCII formatter.
  log.SetFormatter(&log.JSONFormatter{})
  // Only log the warning severity or above.
  log.SetLevel(log.DebugLevel)
}
Enter fullscreen mode Exit fullscreen mode

This code should be included in your application's initialization phase. It configures Logrus to use JSON formatting for log output and sets the log level to include debug messages.

Example with fake error.

package main

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

func init() {
  // Log as JSON instead of the default ASCII formatter.
  log.SetFormatter(&log.JSONFormatter{})
  // Only log the debug severity or above.
  log.SetLevel(log.DebugLevel)
}

func main() {

  ctx := "TestLogrus" //context
  err := errors.New("math: square root of negative number")

  if err != nil {
    log.WithFields(log.Fields{
    "ctx": ctx,
    }).Error(err.Error())
  }

}
Enter fullscreen mode Exit fullscreen mode

Image description

The code snippet provided demonstrates a basic implementation of Logrus in a Go application. Here's a simple explanation of what the code does:

  • An error variable err is created using the errors.New function. In this example, the error message states "math: square root of negative number".

  • The code checks if the error variable is not nil, indicating the occurrence of an error.

  • If an error exists, the Logrus WithFields function is used to add additional fields to the log entry. In this case, the ctx field is included with the value of the ctx variable.

  • Finally, the Error method is called on the Logrus logger to log the error message. The error message itself is retrieved using err.Error().

Additional

func init() {
  // Log as JSON instead of the default ASCII formatter.
  // log.SetFormatter(&log.JSONFormatter{})
  log.SetFormatter(&log.TextFormatter{
    DisableColors: false,
    FullTimestamp: true,
    ForceColors: true,
  })
  // Only log the warning severity or above.
  log.SetLevel(log.DebugLevel)
}
Enter fullscreen mode Exit fullscreen mode

When a TTY is attached, otherwise just plain text
Image description

*https://github.com/sirupsen/logrus

Top comments (0)