首頁 > 軟體

Go實現整合Logrus實現紀錄檔列印

2022-07-04 14:02:43

Github:github.com/sirupsen/lo…

1 初步使用

package main
import (
   "context"
   "github.com/sirupsen/logrus"
)
​
func main() {
   method0()
}
func method0() {
   logger:= logrus.New()
   logger.Warning("This is a first log.")
   ctx := context.WithValue(context.Background(),"key","value")
   logger.Warning(ctx,"This is a second log.")
}

2 增加標籤WithFields

package main​
import (
   "context"
   "github.com/sirupsen/logrus"
)
func main() {
   method1()
}
func method1() {
   log.WithFields(log.Fields{
      "fieldKey": "fieldValue",
   }).Warning("This is a first field log.")
​
   log.WithFields(log.Fields{
      "fieldKey": "fieldValue",
      "fieldKey2": "fieldValue2",
   }).Warning("This is a second field log.")
}

3 設定常見引數

package main
import (
   "context"
   "github.com/sirupsen/logrus"
   log "github.com/sirupsen/logrus"
   "os"
)
​func main() {
   method2()
}
func init() {
   // 紀錄檔作為JSON而不是預設的ASCII格式器.
   log.SetFormatter(&log.JSONFormatter{})
​
   // 輸出到標準輸出,可以是任何io.Writer
   log.SetOutput(os.Stdout)
​
   // 只記錄xx級別或以上的紀錄檔
   log.SetLevel(log.TraceLevel)
}
func method2() {
   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!")
}

Formatter一般分為兩種:

  • &log.JSONFormatter{}
  • &log.TextFormatter{}

紀錄檔級別一共七種:

  • log.Trace()
  • log.Debug()
  • log.Info()
  • log.Warn()
  • log.Error()
  • log.Fatal()
  • log.Panic()

4 輸出紀錄檔到檔案

package main
import (
    "context"
    "github.com/sirupsen/logrus"
    "os"
)
func main() {
    method4()
}
func method4() {
   var log = logrus.New()
   file ,err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
   if err == nil{
      log.Out = file
   }else{
      log.Info("Failed to log to file")
   }
​
   log.WithFields(logrus.Fields{
      "filename": "123.txt",
   }).Info("This is a file log")
}

logrus.log檔案的內容:

time="2022-01-06T13:04:25+08:00" level=info msg="This is a file log" filename=123.txt

5 利用Hooks將紀錄檔輸出到其他地方

import (
  log "github.com/sirupsen/logrus"
  "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake"
  logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
  "log/syslog"
)
func init() {
  // 使用氣閘掛鉤來報告錯誤嚴重程度或以上的錯誤一個異常追蹤。您可以建立自定義勾點,請參見勾點部分。
  log.AddHook(airbrake.NewHook(123, "xyz", "production"))
​
  hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
  if err != nil {
    log.Error("Unable to connect to local syslog daemon")
  } else {
    log.AddHook(hook)
  }
}

只需要在AddHook是新增相應的Hook就可以了

到此這篇關於Go實現整合Logrus實現紀錄檔列印的文章就介紹到這了,更多相關Go Logrus紀錄檔列印內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com