Simplify Logging in Go Applications Configuration Logrus
Tags: go, beginners, codepen, testing
Published: 2023-06-13 04:13:19


## 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](https://github.com/sirupsen/logrus)

<img width="100%" style="width:100%" src="https://media.giphy.com/media/25KEhzwCBBFPb79puo/giphy-downsized.gif">

First, we import the log package from [logrus](github.com/sirupsen/logrus), which is the official Logrus package. Logrus is a popular logging library for Go that provides powerful **features and flexibility**.

```go
package main

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

In the code snippet, the log package is aliased as log from the [logrus](github.com/sirupsen/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.
```go
package main

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

func main() {

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

}
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/byw2s5f3bi3sbo9fmsj1.png)

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.

```go
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")
}
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/as77zv8614ubh7ctj46j.png)

```go
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)
}
```

> 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.
```go
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())
  }
 
}
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aroj8anirv6bxr7xmiqs.png)

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**
```go
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)
}
```

> When a TTY is attached, otherwise just plain text
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p2pyhodwbhgavwrb55jb.png)

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