切換到工做目錄,下載日誌模塊html
cd /data/work/go/
go get github.com/astaxie/beego/logs
使用的時候,須要導入模塊git
import ( "github.com/astaxie/beego/logs" )
輸出文件名和行號,日誌默認不輸出調用的文件名和文件行號,若是你指望輸出調用的文件名和文件行號,能夠以下設置github
logs.EnableFuncCallDepth(true)
開啓傳入參數 true,關閉傳入參數 false,默認是關閉的sql
這是一個用來處理日誌的庫,它的設計思路來自於 database/sql
,目前支持的引擎有 file、console、net、smtpthis
(1)console,命令行輸出,輸出到終端spa
package controllers import ( "github.com/astaxie/beego" "github.com/astaxie/beego/logs" ) type TestController struct { beego.Controller } func (c *TestController) GetData() { log := logs.NewLogger() log.SetLogger(logs.AdapterConsole) log.Debug("this is a debug message") log.Alert("Alert") log.Critical("Critical") }
在終端執行時,看到如下輸出:.net
(2)file,日誌輸出到文件命令行
package controllers import ( "github.com/astaxie/beego" "github.com/astaxie/beego/logs" ) type TestController struct { beego.Controller } func (c *TestController) GetData() { log := logs.NewLogger(10000) // 建立一個日誌記錄器,參數爲緩衝區的大小 log.SetLogger(logs.AdapterFile,`{"filename":"logs/error.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10,"color":true}`) log.SetLevel(logs.LevelDebug) // 設置日誌寫入緩衝區的等級 log.EnableFuncCallDepth(true) // 輸出log時能顯示輸出文件名和行號(非必須) log.Emergency("Emergency") log.Alert("Alert") log.Critical("Critical") log.Error("Error") log.Warning("Warning") log.Notice("Notice") log.Informational("Informational") log.Debug("Debug") log.Flush() // 將日誌從緩衝區讀出,寫入到文件 log.Close() }
備註:若是log.SetLevel(logs.LevelDebug)修改成log.SetLevel(logs.LevelEmergency),則只輸出Emergency級別的log,其餘級別的log不會輸出。
執行,打開error.log,看到以下:debug
2019/02/15 11:47:14.566 [M] [test.go:23] Emergency 2019/02/15 11:47:14.566 [A] [test.go:24] Alert 2019/02/15 11:47:14.566 [C] [test.go:25] Critical 2019/02/15 11:47:14.566 [E] [test.go:26] Error 2019/02/15 11:47:14.566 [W] [test.go:27] Warning 2019/02/15 11:47:14.566 [N] [test.go:28] Notice 2019/02/15 11:47:14.566 [I] [test.go:29] Informational 2019/02/15 11:47:14.566 [D] [test.go:30] Debug 2019/02/15 11:51:03.280 [M] [dict.go:70] Emergency 2019/02/15 11:51:03.280 [A] [dict.go:71] Alert
各個參數的意思以下:設計
(3)multifile
logs.SetLogger(logs.AdapterMultiFile, `{"filename":"test.log","separate":["emergency", "alert", "critical", "error", "warning", "notice", "info", "debug"]}`)
主要的參數以下說明(除 separate 外,均與file相同):
(4)smtp,郵件發送
logs.SetLogger(logs.AdapterMail, `{"username":"beegotest@gmail.com","password":"xxxxxxxx","host":"smtp.gmail.com:587","sendTos":["xiemengjun@gmail.com"]}`)
主要的參數說明以下:
Diagnostic message from server
(5)ElasticSearch,輸出到ElasticSearch
logs.SetLogger(logs.AdapterEs, `{"dsn":"http://localhost:9200/","level":1}`)
LevelEmergency = iota // 緊急級別 LevelAlert // 報警級別 LevelCritical // 嚴重錯誤級別 LevelError // 錯誤級別 LevelWarning // 警告級別 LevelNotice // 注意級別 LevelInformational // 報告級別 LevelDebug // 除錯級別
官方文檔:https://beego.me/docs/module/logs.md
https://www.cnblogs.com/hezhixiong/p/4607365.html
https://blog.csdn.net/huwh_/article/details/77923570