示例
package logsimport ( "os" log "github.com/sirupsen/logrus" "fmt")var Environment stringfunc init() { if Environment == "production" { log.SetFormatter(&log.JSONFormatter{}) log.SetOutput(setLogFile("error.logs")) log.SetLevel(log.WarnLevel) } else { log.SetFormatter(&log.TextFormatter{}) log.SetOutput(os.Stdout) log.SetLevel(log.DebugLevel) }}func setLogFile(filename string) *os.File{ os.MkdirAll("logs",0666) f, err := os.OpenFile("logs/"+ filename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666) if err != nil { fmt.Println("Fail to find", *f, "cServer start Failed") os.Exit(1) } return f}func TestExample() { // 1. 简单的记录单个域 log.WithFields(log.Fields{ "animal": "walrus", "size": 10, }).Info("A group of walrus emerges from the ocean") // 2. 可复用性 contextLogger := log.WithFields(log.Fields{ "common": "this is a common field", "other": "I also should be logged always", }) contextLogger.Info("I'll be logged with common and other field") contextLogger.Info("Me too")}
日志级别
log.Debug("Useful debugging information.")log.Info("Something noteworthy happened!")log.Warn("You should probably take a look at this.")log.Error("Something failed but I'm not quitting.")// Calls os.Exit(1) after logginglog.Fatal("Bye.")// Calls panic() after logginglog.Panic("I'm bailing.")