Hello,
I wanted to set TextFormatter for stdout and JsonFormatter for file output, is that possible?
Here's my logger initialization
func initLogger() {
if debug {
logrus.SetLevel(logrus.DebugLevel)
}
logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: true, // Seems like automatic color detection doesn't work on windows terminals
FullTimestamp: true,
TimestampFormat: time.RFC822,
})
multiWriter := io.MultiWriter(colorable.NewColorableStdout(), &lumberjack.Logger{
Filename: "logs/console.log",
MaxSize: 50, // megabytes
MaxBackups: 3,
MaxAge: 28, //days
Compress: true, // disabled by default
})
logrus.SetOutput(multiWriter)
}
I am logging into Stdout and log file
The problem is that it output color chars are getting inside the file as well..
[36mINFO[0m[04 Jul 18 17:12 EEST] Initializing
Solved by using hooks:
func initLogger() {
var logLevel = logrus.InfoLevel
if debug {
logLevel = logrus.DebugLevel
}
rotateFileHook, err := rotatefilehook.NewRotateFileHook(rotatefilehook.RotateFileConfig{
Filename: "logs/console.log",
MaxSize: 50, // megabytes
MaxBackups: 3,
MaxAge: 28, //days
Level: logLevel,
Formatter: &logrus.JSONFormatter{
TimestampFormat: time.RFC822,
},
})
if err != nil {
logrus.Fatalf("Failed to initialize file rotate hook: %v", err)
}
logrus.SetLevel(logLevel)
logrus.SetOutput(colorable.NewColorableStdout())
logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: true,
FullTimestamp: true,
TimestampFormat: time.RFC822,
})
logrus.AddHook(rotateFileHook)
}
Thanks for the solution, but I find it somewhat overkilling to add another dependency (lumberjack) just to solve a simple problem, namely writing logs to file in different format. Can we consider re-open this issue? thanks
@UnAfraid How do you have two different outputs/formatters using vanilla logrus?
@UnAfraid How do you have two different outputs/formatters using vanilla logrus?
By using hook, either existing one or implement your own
Agree this should be re-opened, having a trivial way to configure a formatter for the built-in hooks is a must.
Most helpful comment
Solved by using hooks: