切换到工做目录,下载日志模块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