溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在golang 中使用Logrus

發(fā)布時間:2021-05-25 16:02:23 來源:億速云 閱讀:251 作者:Leah 欄目:編程語言

如何在golang 中使用Logrus?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

golang Logrus簡易使用教程

使用Logrus的最簡單方法:

package main
import (
  log "github.com/sirupsen/logrus"
)
func main() {
  log.WithFields(log.Fields{
    "animal": "walrus",
  }).Info("A walrus appears")
}

請注意,它與stdlib記錄器完全api兼容,因此您可以在log任何地方替換導入,log "github.com/sirupsen/logrus" 。也可以自定義所有內(nèi)容:

package main
import (
  "os"
  log "github.com/sirupsen/logrus"
)
func init() {
  // Log 為JSON而不是默認的ASCII格式。
  log.SetFormatter(&log.JSONFormatter{})
  // 輸出到標準輸出,而不是默認的標準錯誤
  //可以是任何io.Writer,請參閱下面的文件例如日志。
  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!")
  // 一種常見的模式是通過重用
  //從WithFields返回的logrus.Entry 來重用日志記錄語句之間的字段
  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實例,即logger對象,來記錄項目所有的日志。示例如下:

package main
import (
  "os"
  "github.com/sirupsen/logrus"
)
// 創(chuàng)建記錄器的一個新實例。您可以有任意多個實例
var log = logrus.New()
func main() {
  // 用于設置屬性的API與程序包級別
  // 導出的記錄器有些不同。見Godoc。
  log.Out = os.Stdout
  // 您可以將其設置為任何`io.Writer`
  // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  // if err == nil {
  //  log.Out = file
  // } else {
  //  log.Info("Failed to log to file, using default stderr")
  // }
  log.WithFields(logrus.Fields{
    "animal": "walrus",
    "size":   10,
  }).Info("A group of walrus emerges from the ocean")
}

Fields:

Logrus鼓勵通過日志記錄字段而不是冗長且無法解析的錯誤消息進行仔細的結(jié)構(gòu)化日志記錄。例如,代替:log.Fatalf("Failed to send event %s to topic %s with key %d"),您應該使用:

log.WithFields(log.Fields{
  "event": event,
  "topic": topic,
  "key": key,
}).Fatal("Failed to send event")

我們發(fā)現(xiàn)此API會迫使您考慮以產(chǎn)生更多有用日志消息的方式進行日志記錄。我們曾經(jīng)遇到過無數(shù)種情況,在該情況下,僅向已存在的日志語句添加一個字段就可以為我們節(jié)省時間。該WithFields呼叫是可選的。

通常,使用Logrus使用printf-family函數(shù)中的任何一個應被視為提示,您應該添加一個字段,但是,您仍然可以將 printf-family函數(shù)與Logrus一起使用。

默認字段

將字段始終附加到應用程序或應用程序的一部分中的日志語句通常會很有幫助。例如,您可能希望始終在請求的上下文中記錄 request_id和user_ip。無需log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})在每一行上都寫 ,而是可以創(chuàng)建一個logrus.Entry傳遞:

requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
requestLogger.Info("something happened on that request") # will log request_id and user_ip
requestLogger.Warn("something not great happened")

Hooks

您可以添加用于日志記錄級別的掛鉤。例如,將錯誤發(fā)送到上的異常跟蹤服務Error,F(xiàn)atal并將Panic信息發(fā)送到StatsD或同時記錄到多個位置,例如syslog。

Logrus帶有內(nèi)置掛鉤。在其中添加這些或您的自定義鉤子 init:

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() {
  // Use the Airbrake hook to report errors that have Error severity or above to
  // an exception tracker. You can create custom hooks, see the Hooks section.
  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)
  }
}

注意:Syslog鉤子還支持連接到本地syslog(例如“ / dev / log”或“ / var / run / syslog”或“ / var / run / log”)。有關詳細信息,請檢查syslog掛鉤README。

可以在此Wiki 頁面中找到當前已知的服務掛鉤的列表。

日志記錄級別

Logrus具有七個日志記錄級別:跟蹤,調(diào)試,信息,警告,錯誤,嚴重和緊急。

log.Trace("Something very low level.")
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 logging
log.Fatal("Bye.")
// Calls panic() after logging
log.Panic("I'm bailing.")

您可以在上設置日志記錄級別Logger,然后它將僅記錄具有該嚴重性或更高嚴重性的條目:

// Will log anything that is info or above (warn, error, fatal, panic). Default.
log.SetLevel(log.InfoLevel)

log.Level = logrus.DebugLevel如果應用程序具有調(diào)試或詳細環(huán)境,則在其中進行設置可能會很有用。

參賽作品

除了添加的字段WithField或WithFields某些字段外,還會自動將其添加到所有日志記錄事件中:

time。創(chuàng)建條目的時間戳。

msg。呼叫{Info,Warn,Error,Fatal,Panic}后傳遞到的日志消息AddFields。例如Failed to send event.

level。日志記錄級別。例如info。

環(huán)境

Logrus沒有環(huán)境概念。

如果希望只在特定環(huán)境中使用鉤子和格式化程序,則應自己處理。例如,如果您的應用程序具有全局變量Environment,它是環(huán)境的字符串表示形式,則可以執(zhí)行以下操作:

import (
  log "github.com/sirupsen/logrus"
)
init() {
  // do something here to set environment depending on an environment variable
  // or command-line flag
  if Environment == "production" {
    log.SetFormatter(&log.JSONFormatter{})
  } else {
    // The TextFormatter is default, you don't actually have to do this.
    log.SetFormatter(&log.TextFormatter{})
  }
}

此配置是按logrus預期方式使用的,但是生產(chǎn)中的JSON僅在使用Splunk或Logstash等工具進行日志聚合時才有用。

格式化程序

內(nèi)置的日志格式器是:

logrus.TextFormatter。如果stdout是tty,則以彩色記錄事件,否則以彩色記錄事件。

注意:要在沒有TTY時強制輸出彩色,請將ForceColors 字段設置為true。即使有TTY,也要不強制輸出彩色,請將DisableColors字段設置 為true。對于Windows,請參閱 github.com/mattn/go-colorable。

啟用顏色后,默認情況下級別將被截斷為4個字符。要禁用截斷功能,請將DisableLevelTruncation字段設置為true。

輸出到TTY時,以可視方式向下掃描所有級別均為相同寬度的列通常會很有幫助。通過在級別文本中添加填充,將PadLevelText字段設置為true啟用此行為。

所有選項都在生成的文檔中列出。

logrus.JSONFormatter。將字段記錄為JSON。

所有選項都在生成的文檔中列出。

第三方日志格式化程序:

FluentdFormatter。格式化可由Kubernetes和Google Container Engine解析的條目。

GELF。格式化條目,使其符合Graylog的GELF 1.1規(guī)范。

logstash。將字段記錄為Logstash事件。

prefixed。顯示日志條目源以及備用布局。

zalgo。調(diào)用Zalgo的力量。

nested-logrus-formatter。將對數(shù)字段轉(zhuǎn)換為嵌套結(jié)構(gòu)。

powerful-logrus-formatter。打印日志時獲取文件名,日志行號和最新函數(shù)名稱;Sava日志到文件。

caption-json-formatter。添加了人類可讀標題的logrus消息json格式化程序。

您可以通過實現(xiàn)Formatter接口(需要一種Format方法)來定義格式化程序。Format需要一個*Entry。entry.Data是一種 Fields類型(map[string]interface{}),其中包含您的所有字段以及默認字段(請參見上面的條目部分):

type MyJSONFormatter struct {
}
log.SetFormatter(new(MyJSONFormatter))
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
  // Note this doesn't include Time, Level and Message which are available on
  // the Entry. Consult `godoc` on information about those fields or read the
  // source of the official loggers.
  serialized, err := json.Marshal(entry.Data)
    if err != nil {
      return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
    }
  return append(serialized, '\n'), nil
}

記錄為 io.Writer

Logrus可以轉(zhuǎn)換為io.Writer。該作家是an的結(jié)尾,io.Pipe您有責任關閉它。

w := logger.Writer()
defer w.Close()
srv := http.Server{
    // create a stdlib log.Logger that writes to
    // logrus.Logger.
    ErrorLog: log.New(w, "", 0),
}

寫入該寫入器的每一行都將使用格式化程序和鉤子以常規(guī)方式打印。這些條目的級別為info。

這意味著我們可以輕松覆蓋標準庫記錄器:

logger := logrus.New()
logger.Formatter = &logrus.JSONFormatter{}
// Use logrus for standard log output
// Note that `log` here references stdlib's log
// Not logrus imported under the name `log`.
log.SetOutput(logger.Writer())

golang的優(yōu)點

golang是一種編譯語言,可以將代碼編譯為機器代碼,編譯后的二進制文件可以直接部署到目標機器而無需額外的依賴,所以golang的性能優(yōu)于其他的解釋性語言,且可以在golang中使用goroutine來實現(xiàn)并發(fā)性,它提供了一個非常優(yōu)雅的goroutine調(diào)度程序系統(tǒng),可以很容易地生成數(shù)百萬個goroutine。

關于如何在golang 中使用Logrus問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI