golang日誌框架之logrus的使用

這篇文章主要介紹了golang日誌框架之logrus的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

golang日誌庫

golang標準庫的日誌框架非常簡單,僅僅提供了print,panic和fatal三個函數對於更精細的日誌級別、日誌文件分割以及日誌分發等方面並沒有提供支持。所以催生了很多第三方的日誌庫,但是在golang的世界裏,沒有一個日誌庫像slf4j那樣在Java中具有絕對統治地位。golang中,流行的日誌框架包括logrus、zap、zerolog、seelog等。

logrus是目前Github上star數量最多的日誌庫,目前(2018.08,下同)star數量爲8119,fork數爲1031。logrus功能強大,性能高效,而且具有高度靈活性,提供了自定義插件的功能。很多開源項目,如docker,prometheus等,都是用了logrus來記錄其日誌。

zap是Uber推出的一個快速、結構化的分級日誌庫。具有強大的ad-hoc分析功能,並且具有靈活的儀表盤。zap目前在GitHub上的star數量約爲4.3k。

seelog提供了靈活的異步調度、格式化和過濾功能。目前在GitHub上也有約1.1k。

logrus特性

logrus具有以下特性:

  • 完全兼容golang標準庫日誌模塊:logrus擁有六種日誌級別:debug、info、warn、error、fatal和panic,這是golang標準庫日誌模塊的API的超集。如果您的項目使用標準庫日誌模塊,完全可以以最低的代價遷移到logrus上。
  • 可擴展的Hook機制:允許使用者通過hook的方式將日誌分發到任意地方,如本地文件系統、標準輸出、logstash、elasticsearch或者mq等,或者通過hook定義日誌內容和格式等。
  • 可選的日誌輸出格式:logrus內置了兩種日誌格式,JSONFormatter和TextFormatter,如果這兩個格式不滿足需求,可以自己動手實現接口Formatter,來定義自己的日誌格式。
  • Field機制:logrus鼓勵通過Field機制進行精細化的、結構化的日誌記錄,而不是通過冗長的消息來記錄日誌。
  • logrus是一個可插拔的、結構化的日誌框架。

logrus的使用

第一個示例

最簡單的使用logrus的示例如下:

package main

import (
 log "github.com/sirupsen/logrus"
)

func main() {
 log.WithFields(log.Fields{
  "animal": "walrus",
 }).Info("A walrus appears")
}

上面代碼執行後,標準輸出上輸出如下:

time="2018-08-11T15:42:22+08:00" level=info msg="A walrus appears" animal=walrus

logrus與golang標準庫日誌模塊完全兼容,因此您可以使用log“github.com/sirupsen/logrus”替換所有日誌導入。
logrus可以通過簡單的配置,來定義輸出、格式或者日誌級別等。

package main

import (
  "os"
  log "github.com/sirupsen/logrus"
)

func init() {
  // 設置日誌格式爲json格式
  log.SetFormatter(&log.JSONFormatter{})

  // 設置將日誌輸出到標準輸出(默認的輸出爲stderr,標準錯誤)
  // 日誌消息輸出可以是任意的io.writer類型
  log.SetOutput(os.Stdout)

  // 設置日誌級別爲warn以上
  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!")
}

Logger

logger是一種相對高級的用法, 對於一個大型項目, 往往需要一個全局的logrus實例,即logger對象來記錄項目所有的日誌。如:

package main

import (
  "github.com/sirupsen/logrus"
  "os"
)

// logrus提供了New()函數來創建一個logrus的實例。
// 項目中,可以創建任意數量的logrus實例。
var log = logrus.New()

func main() {
  // 爲當前logrus實例設置消息的輸出,同樣地,
  // 可以設置logrus實例的輸出到任意io.writer
  log.Out = os.Stdout

  // 爲當前logrus實例設置消息輸出格式爲json格式。
  // 同樣地,也可以單獨爲某個logrus實例設置日誌級別和hook,這裏不詳細敘述。
  log.Formatter = &logrus.JSONFormatter{}

  log.WithFields(logrus.Fields{
    "animal": "walrus",
    "size":  10,
  }).Info("A group of walrus emerges from the ocean")
}

Fields

前一章提到過,logrus不推薦使用冗長的消息來記錄運行信息,它推薦使用Fields來進行精細化的、結構化的信息記錄。
例如下面的記錄日誌的方式:

log.Fatalf("Failed to send event %s to topic %s with key %d", event, topic, key)
````

在logrus中不太提倡,logrus鼓勵使用以下方式替代之:





<div class="se-preview-section-delimiter"></div>

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

前面的WithFields API可以規範使用者按照其提倡的方式記錄日誌。但是WithFields依然是可選的,因爲某些場景下,使用者確實只需要記錄儀一條簡單的消息。

通常,在一個應用中、或者應用的一部分中,都有一些固定的Field。比如在處理用戶http請求時,上下文中,所有的日誌都會有request_iduser_ip。爲了避免每次記錄日誌都要使用log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}),我們可以創建一個logrus.Entry實例,爲這個實例設置默認Fields,在上下文中使用這個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")

Hook

logrus最令人心動的功能就是其可擴展的HOOK機制了,通過在初始化時爲logrus添加hook,logrus可以實現各種擴展功能。

Hook接口

logrus的hook接口定義如下,其原理是每此寫入日誌時攔截,修改logrus.Entry。

// logrus在記錄Levels()返回的日誌級別的消息時會觸發HOOK,
// 按照Fire方法定義的內容修改logrus.Entry。
type Hook interface {
  Levels() []Level
  Fire(*Entry) error
}

一個簡單自定義hook如下,DefaultFieldHook定義會在所有級別的日誌消息中加入默認字段appName="myAppName"

type DefaultFieldHook struct {
}

func (hook *DefaultFieldHook) Fire(entry *log.Entry) error {
  entry.Data["appName"] = "MyAppName"
  return nil
}

func (hook *DefaultFieldHook) Levels() []log.Level {
  return log.AllLevels
}

hook的使用也很簡單,在初始化前調用log.AddHook(hook)添加相應的hook即可。

logrus官方僅僅內置了syslog的hook

此外,但Github也有很多第三方的hook可供使用,文末將提供一些第三方HOOK的連接。

問題與解決方案

儘管logrus有諸多優點,但是爲了靈活性和可擴展性,官方也削減了很多實用的功能,例如:

  • 沒有提供行號和文件名的支持
  • 輸出到本地文件系統沒有提供日誌分割功能
  • 官方沒有提供輸出到ELK等日誌處理中心的功能

但是這些功能都可以通過自定義hook來實現。

記錄文件名和行號

logrus的一個很致命的問題就是沒有提供文件名和行號,這在大型項目中通過日誌定位問題時有諸多不便。Github上的logrus的issue#63:Log filename and line number創建於2014年,四年過去了仍是open狀態~~~
網上給出的解決方案分位兩類,一就是自己實現一個hook;二就是通過裝飾器包裝logrus.Entry。兩種方案網上都有很多代碼,但是大多無法正常工作。但總體來說,解決問題的思路都是對的:通過標準庫的runtime模塊獲取運行時信息,並從中提取文件名,行號和調用函數名。

標準庫runtime模塊的Caller(skip int)函數可以返回當前goroutine調用棧中的文件名,行號,函數信息等,參數skip表示表示返回的棧幀的層次,0表示runtime.Caller的調用着。返回值包括響應棧幀層次的pc(程序計數器),文件名和行號信息。爲了提高效率,我們先通過跟蹤調用棧發現,從runtime.Caller()的調用者開始,到記錄日誌的生成代碼之間,大概有8到11層左右,所有我們在hook中循環第8到11層調用棧應該可以找到日誌記錄的生產代碼。

這裏寫圖片描述 

此外,runtime.FuncForPC(pc uintptr) *Func可以返回指定pc的函數信息。

所有我們要實現的hook也是基於以上原理,使用runtime.Caller()依次循環調用棧的第7~11層,過濾掉sirupsen包內容,那麼第一個非siupsenr包就認爲是我們的生產代碼了,並返回pc以便通過runtime.FuncForPC()獲取函數名稱。然後將文件名、行號和函數名組裝爲source字段塞到logrus.Entry中即可。

time="2018-08-11T19:10:15+08:00" level=warning msg="postgres_exporter is ready for scraping on 0.0.0.0:9295..." source="postgres_exporter/main.go:60:main()"
time="2018-08-11T19:10:17+08:00" level=error msg="!!!msb info not found" source="postgres/postgres_query.go:63:QueryPostgresInfo()"
time="2018-08-11T19:10:17+08:00" level=error msg="get postgres instances info failed, scrape metrics failed, error:msb env not found" source="collector/exporter.go:71:Scrape()"

日誌本地文件分割

logrus本身不帶日誌本地文件分割功能,但是我們可以通過file-rotatelogs進行日誌本地文件分割。 每次當我們寫入日誌的時候,logrus都會調用file-rotatelogs來判斷日誌是否要進行切分。關於本地日誌文件分割的例子網上很多,這裏不再詳細介紹,奉上代碼:

import (
  "github.com/lestrrat-go/file-rotatelogs"
  "github.com/rifflock/lfshook"
  log "github.com/sirupsen/logrus"
  "time"
)

func newLfsHook(logLevel *string, maxRemainCnt uint) log.Hook {
  writer, err := rotatelogs.New(
    logName+".%Y%m%d%H",
    // WithLinkName爲最新的日誌建立軟連接,以方便隨着找到當前日誌文件
    rotatelogs.WithLinkName(logName),

    // WithRotationTime設置日誌分割的時間,這裏設置爲一小時分割一次
    rotatelogs.WithRotationTime(time.Hour),

    // WithMaxAge和WithRotationCount二者只能設置一個,
    // WithMaxAge設置文件清理前的最長保存時間,
    // WithRotationCount設置文件清理前最多保存的個數。
    //rotatelogs.WithMaxAge(time.Hour*24),
    rotatelogs.WithRotationCount(maxRemainCnt),
  )

  if err != nil {
    log.Errorf("config local file system for logger error: %v", err)
  }

  level, ok := logLevels[*logLevel]

  if ok {
    log.SetLevel(level)
  } else {
    log.SetLevel(log.WarnLevel)
  }

  lfsHook := lfshook.NewHook(lfshook.WriterMap{
    log.DebugLevel: writer,
    log.InfoLevel: writer,
    log.WarnLevel: writer,
    log.ErrorLevel: writer,
    log.FatalLevel: writer,
    log.PanicLevel: writer,
  }, &log.TextFormatter{DisableColors: true})

  return lfsHook
}

使用上述本地日誌文件切割的效果如下:

這裏寫圖片描述

將日誌發送到elasticsearch

將日誌發送到elasticsearch是很多日誌監控系統的選擇,將logrus日誌發送到elasticsearch的原理是在hook的每次fire調用時,使用golang的es客戶端將日誌信息寫到elasticsearch。elasticsearch官方沒有提供golang客戶端,但是有很多第三方的go語言客戶端可供使用,我們選擇elastic。elastic提供了豐富的文檔,以及Java中的流式接口,使用起來非常方便。

client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
  if err != nil {
    log.Panic(err)
  }

// Index a tweet (using JSON serialization)
tweet1 := Tweet{User: "olivere", Message: "Take Five", Retweets: 0}
put1, err := client.Index().
  Index("twitter").
  Type("tweet").
  Id("1").
  BodyJson(tweet1).
  Do(context.Background())

考慮到logrus的Fields機制,可以實現如下數據格式:

msg := struct {
  Host   string
  Timestamp string `json:"@timestamp"`
  Message  string
  Data   logrus.Fields
  Level   string
}

其中Host記錄產生日誌主機信息,在創建hook是指定。其他數據需要從logrus.Entry中取得。測試過程我們選擇按照此原理實現的第三方HOOK:elogrus。其使用如下:

import (
  "github.com/olivere/elastic"
  "gopkg.in/sohlich/elogrus"
)

func initLog() {
  client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
  if err != nil {
    log.Panic(err)
  }
  hook, err := elogrus.NewElasticHook(client, "localhost", log.DebugLevel, "mylog")
  if err != nil {
    log.Panic(err)
  }
  log.AddHook(hook)
}

從Elasticsearch查詢得到日誌存儲,效果如下:

GET http://localhost:9200/mylog/_search

HTTP/1.1 200 OK
content-type: application/json; charset=UTF-8
transfer-encoding: chunked

{
 "took": 1,
 "timed_out": false,
 "_shards": {
  "total": 5,
  "successful": 5,
  "failed": 0
 },
 "hits": {
  "total": 2474,
  "max_score": 1.0,
  "hits": [
   {
    "_index": "mylog",
    "_type": "log",
    "_id": "AWUw13jWnMZReb-jHQup",
    "_score": 1.0,
    "_source": {
     "Host": "localhost",
     "@timestamp": "2018-08-13T01:12:32.212818666Z",
     "Message": "!!!msb info not found",
     "Data": {},
     "Level": "ERROR"
    }
   },
   {
    "_index": "mylog",
    "_type": "log",
    "_id": "AWUw13jgnMZReb-jHQuq",
    "_score": 1.0,
    "_source": {
     "Host": "localhost",
     "@timestamp": "2018-08-13T01:12:32.223103348Z",
     "Message": "get postgres instances info failed, scrape metrics failed, error:msb env not found",
     "Data": {
      "source": "collector/exporter.go:71:Scrape()"
     },
     "Level": "ERROR"
    }
   },
   //...
   {
    "_index": "mylog",
    "_type": "log",
    "_id": "AWUw2f1enMZReb-jHQu_",
    "_score": 1.0,
    "_source": {
     "Host": "localhost",
     "@timestamp": "2018-08-13T01:15:17.212546892Z",
     "Message": "!!!msb info not found",
     "Data": {
      "source": "collector/exporter.go:71:Scrape()"
     },
     "Level": "ERROR"
    }
   },
   {
    "_index": "mylog",
    "_type": "log",
    "_id": "AWUw2NhmnMZReb-jHQu1",
    "_score": 1.0,
    "_source": {
     "Host": "localhost",
     "@timestamp": "2018-08-13T01:14:02.21276903Z",
     "Message": "!!!msb info not found",
     "Data": {},
     "Level": "ERROR"
    }
   }
  ]
 }
}

將日誌發送到其他位置

將日誌發送到日誌中心也是logrus所提倡的,雖然沒有提供官方支持,但是目前Github上有很多第三方hook可供使用:

logrus_amqp:Logrus hook for Activemq。

logrus-logstash-hook:Logstash hook for logrus。

mgorus:Mongodb Hooks for Logrus。

logrus_influxdb:InfluxDB Hook for Logrus。

logrus-redis-hook:Hook for Logrus which enables logging to RELK stack (Redis, Elasticsearch, Logstash and Kibana)。

等等,上述第三方hook我這裏沒有具體驗證,大家可以根據需要自行嘗試。

其他注意事項

Fatal處理

和很多日誌框架一樣,logrus的Fatal系列函數會執行os.Exit(1)。但是logrus提供可以註冊一個或多個fatal handler函數的接口logrus.RegisterExitHandler(handler func() {} ),讓logrus在執行os.Exit(1)之前進行相應的處理。fatal handler可以在系統異常時調用一些資源釋放api等,讓應用正確的關閉。

線程安全

默認情況下,logrus的api都是線程安全的,其內部通過互斥鎖來保護併發寫。互斥鎖工作於調用hooks或者寫日誌的時候,如果不需要鎖,可以調用logger.SetNoLock()來關閉之。可以關閉logrus互斥鎖的情形包括:

  • 沒有設置hook,或者所有的hook都是線程安全的實現。
  • 寫日誌到logger.Out已經是線程安全的了,如logger.Out已經被鎖保護,或者寫文件時,文件是以O_APPEND方式打開的,並且每次寫操作都小於4k。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章