Skip to content

Instantly share code, notes, and snippets.

@huobazi
Last active March 22, 2023 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huobazi/80805158fe1f2cac7170fe68c37741ab to your computer and use it in GitHub Desktop.
Save huobazi/80805158fe1f2cac7170fe68c37741ab to your computer and use it in GitHub Desktop.
golang, logrus, write log to stdout also write to files as the same time with different format
package logging
import (
"time"
"github.com/sirupsen/logrus"
"github.com/snowzach/rotatefilehook"
"github.com/mattn/go-colorable"
)
type logger struct { *logrus.Logger}
func (l *logger) Say(msg string){
l.Info(msg)
}
func (l *logger) Sayf(fmt string, args ...interface{}){
l.Infof(fmt,args)
}
func (l *logger) SayWithField(msg string, k string, v interface{}){
l.WithField(k,v).Info(msg)
}
func (l *logger) SayWithFields(msg string, fields map[string] interface{}){
l.WithFields(fields).Info(msg)
}
func NewLogger() *logger{
logLevel := logrus.InfoLevel
log := logrus.New()
log.SetLevel(logLevel)
rotateFileHook, err := rotatefilehook.NewRotateFileHook(rotatefilehook.RotateFileConfig{
Filename: "logs/console.log",
MaxSize: 50, // megabytes
MaxBackups: 3, // amouts
MaxAge: 28, //days
Level: logLevel,
Formatter: &logrus.JSONFormatter{
TimestampFormat: time.RFC822,
},
})
if err != nil {
logrus.Fatalf("Failed to initialize file rotate hook: %v", err)
}
log.SetOutput(colorable.NewColorableStdout())
log.SetFormatter(&logrus.TextFormatter{
PadLevelText :true,
ForceColors: true,
FullTimestamp: true,
TimestampFormat : "2006-01-02 15:04:05",
})
log.AddHook(rotateFileHook)
return &logger{log}
}
package main
import (
"logrus-test/logging"
)
func main() {
log := logging.NewLogger()
log.Info("Hello Info")
log.Warn("Hello Warn")
log.WithField("int",123).WithField("string","haha").Error("Hello Error")
log.Say("Hello Say")
log.Sayf("Hello Say %d", 123)
log.SayWithField("Say with field", "int", 1)
log.SayWithFields("Say with field", map[string]interface{}{
"animal": "walrus",
"val": 123,
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment