這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
一、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")) // ..........}
效果如下: