发布于 5年前
                Go日志框架logrus的基本用法
以package级别方式使用logrus
package main
import (
  "os"
  log "github.com/sirupsen/logrus"
)
func init() {
  // 设置日志格式
  log.SetFormatter(&log.JSONFormatter{})
  // 设置输出
  log.SetOutput(os.Stdout)
  // 设置日志级别
  log.SetLevel(log.WarnLevel)
}
func main() {
  log.WithFields(log.Fields{
    "animal": "walrus",
    "size":   10,
  }).Info("A group of walrus emerges from the ocean")
  log.WithFields(log.Fields{
    "omg":    true,
    "number": 122,
  }).Warn("The group's number increased tremendously!")
  log.WithFields(log.Fields{
    "omg":    true,
    "number": 100,
  }).Fatal("The ice breaks!")
  // 设置日志默认的信息,所有使用contextLogger都会复用这些信息
  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")
}以实例方式使用logrus
package main
import (
  "os"
  "github.com/sirupsen/logrus"
)
// 创建一个logrus示例
var log = logrus.New()
func main() {
  // 设置输出,这和package的方式有所不同,它是以属性的方式赋值
  log.Out = os.Stdout
  log.WithFields(logrus.Fields{
    "animal": "walrus",
    "size":   10,
  }).Info("A group of walrus emerges from the ocean")
}日志格式
logrus内置的日志格式有两种:
- logrus.TextFormatter:纯文本
- logrus.JSONFormatter:JSON
 
             
             
             
             
            