I come from a node.js background and am comfortable with a number of loggers (such as winston) that allow configurable formatted output to multiple sources such as the console as well as a log file, where the outputs to each may be formatted differently.
I am attempting to do something similar with GoLang and have had difficulty finding a logging package that supports this capability.
Is there a GoLang package that I could use to achieve this outcome?
logrus is already mentioned here and it can give you exactly what you need using hooks. Hooks can send the log to different destinations, using different formats. You can find a list of hooks in the documentation like for sending logs to InfluxDB or Logstash. You can even implement your own hook based on your needs.
Below is an example of achieving this with Sirupsen/logrus
package main
import (
"github.com/Sirupsen/logrus"
"os"
)
// Create a new instance of the logger. You can have any number of instances.
var log1 = logrus.New()
var log2 = logrus.New()
func main() {
// The API for setting attributes is a little different than the package level
// exported logger. See Godoc.
log1.Out = os.Stderr
log1.Formatter = &logrus.TextFormatter{}
LogOutputFile, err := os.OpenFile("out.log", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
logrus.Fatalf("error opening file: %v", err)
}
log2.Out = LogOutputFile
log2.Formatter = &logrus.JSONFormatter{}
log1.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
log2.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With