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")
}
You could use rlog. We developed this to be a very configurable and light weight logger, without any dependencies aside from the standard Golang library.
By default it just logs to stderr or stdout, but you can also specify a logfile instead or in addition to the normal output, which is exactly what you are asking for.
Currently, it doesn't support the idea of different output formats in that case. Could you please give me an example of the different formats you would want to see? Maybe we can implement it.