由淺入深談日誌(Go語言描述)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

一、Basic:日誌工具庫

1、後台輸出

package mainimport (  "fmt")func main(){  fmt.Println("------hello world-----")}

2、There are no exceptions in Golang, only errors.

package mainimport (    "log"    "errors"    "fmt")func main() {   /* local variable definition */  ...   /* function for division which return an error if divide by 0 */   ret,err = div(a, b)if err != nil { log.Fatal(err)    }    fmt.Println(ret)}

3、寫入記錄檔:

package mainimport (  "log"  "os")func main(){  f,err :=os.OpenFile("test.log",os.O_WRONLY|os.O_CREATE|os.O_APPEND,0644)  if err !=nil{    log.Fatal(err)  }  defer f.Close()  log.SetOutput(f)  log.Println("==========works==============")}
YRMacBook-Pro:go-log yanrui$ more test.log2017/05/24 21:46:25 ==========works==============

二、格式化

推薦日誌工具庫:logrus

$ go get github.com/Sirupsen/logrus

1、JSON format

package mainimport (  log "github.com/Sirupsen/logrus"  "github.com/logmatic/logmatic-go")func main() {    // use JSONFormatter    log.SetFormatter(&logmatic.JSONFormatter{})    // log an event as usual with logrus    log.WithFields(log.Fields{"string": "foo", "int": 1, "float": 1.1 }).Info("My first ssl event from golang")}

日誌輸出樣式:

{  "@marker":["sourcecode","golang"],  "date":"2017-05-24T15:27:40+08:00",  "float":1.1,"int":1,"level":"info",  "message":"My first ssl event from golang",  "string":"foo"}

三、附加上下文

通過logrus庫可以加入一些上下文資訊,例如:主機名稱,程式名稱或者會話參數等。

contextLogger := log.WithFields(log.Fields{  "common": "XXX common content XXX",  "other": "YYY special context YYY",})contextLogger.Info("AAAAAAAAAAAA")contextLogger.Info("BBBBBBBBBBBB")

日誌輸出樣式:

YRMacBook-Pro:go-log yanrui$ go run LogMatic.go{"@marker":["sourcecode","golang"],"common":"XXX common content XXX","date":"2017-05-24T17:00:08+08:00","level":"info","message":"AAAAAAAAAAAA","other":"YYY special context YYY"}{"@marker":["sourcecode","golang"],"common":"XXX common content XXX","date":"2017-05-24T17:00:08+08:00","level":"info","message":"BBBBBBBBBBBB","other":"YYY special context YYY"}YRMacBook-Pro:go-log yanrui$

四、Hooks

我們還可以利用Hook機制實現日誌功能擴充,例如Syslog hook,將輸出的日誌發送到指定的Syslog服務。

package mainimport (  log "github.com/sirupsen/logrus"  "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake"  logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"  "log/syslog")func main(){    hook, err := logrus_syslog.NewSyslogHook("udp", "59.37.0.1:514", syslog.LOG_INFO, "")    if err != nil {      log.Error("Unable to connect to local syslog daemon")    } else {      log.AddHook(hook)    }}

驗證是否發送Syslog:

$ sudo tcpdump | grep 127.0.0.3tcpdump: data link type PKTAPtcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on pktap, link-type PKTAP (Apple DLT_PKTAP), capture size 262144 bytes18:51:05.663612 IP 192.168.199.15.58819 > 127.0.0.3.syslog: SYSLOG kernel.info, length: 31418:51:05.663657 IP 192.168.199.15.58819 > 127.0.0.3.syslog: SYSLOG kernel.info, length: 314

五、可視化

在真實情境中日誌資料體量非常龐大,日誌儲存只是第一步,更多的情況是需要查看特定指標或者能夠快速檢索資訊,此時日誌分析平台就發揮作用了。以logmatic為例,可以在它的官網註冊https://logmatic.io/,免費體驗。

在使用logmatic之前,需要下載它的hook支援:

$ go get github.com/logmatic/logmatic-go
func main() {    // instantiate a new Logger with your Logmatic APIKey    // 國內訪問比較慢      log.AddHook(logmatic.NewLogmaticHook("p53uTkOhSEqI3-116DynkQ"))    // ..........}

效果如下:



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.