How to store output of logrus to some variable?

1.3k Views Asked by At

This is code that converts the entered value to JSON format. It shows the correct output but I want to store that output and return it using fmt.Printf

package main

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

func main() {
    log.SetFormatter(&log.JSONFormatter{})
    standardFields := log.Fields{
        "Number of threads": "1",
        "Odd number":        "3",
    }
    log.WithFields(standardFields).Info("Golang")
}
1

There are 1 best solutions below

0
Eli Bendersky On

When you create a new logger with logrus.New(), you can provide the Out field to point to any io.Writer you wish. Here's the documentation for this field:

type Logger struct {
    // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
    // file, or leave it default which is `os.Stderr`. You can also set this to
    // something more adventurous, such as logging to Kafka.
    Out io.Writer
    ...
    ...

So, for example you could create a new bytes.Buffer and set that as the Out field. This is akin to "logging to a variable".

Similarly, you can set the output of the default logger with the SetOutput function.