- 自定义
Writer接口 - 使用示例1,实现日志
HOOK - 使用示例2,整合
graylog
自定义Writer接口
glog模块实现了标准输出以及文件输出的日志内容打印。当然,开发者也可以通过自定义io.Writer接口实现自定义的日志内容输出。io.Writer是标准库提供的内容输出接口,其定义如下:
type Writer interface {Write(p []byte) (n int, err error)}
我们可以通过SetWriter方法或者链式方法To来实现自定义Writer输出,开发者可以在该Writer中实现定义的操作,也可以在其中整合其他的模块功能。
此外,glog.Logger对象已经实现了io.Writer接口,因此开发者可以非常方便地将glog整合使用到其他的模块中。
使用示例1,实现日志HOOK
在该示例中,我们实现了一个自定义的Writer对象MyWriter,在该对象实现的Writer接口中我们对日志内容进行判断,如果出现了PANI或者FATA错误,那么表示是非常严重的错误,该接口将会第一时间通过HTTP接口告知Monitor监控服务。随后再将日志内容通过glog模块按照配置写入到文件和标准输出。
package mainimport ("fmt""github.com/gogf/gf/g/net/ghttp""github.com/gogf/gf/g/os/glog""github.com/gogf/gf/g/text/gregex")type MyWriter struct {logger *glog.Logger}func (w *MyWriter) Write(p []byte) (n int, err error) {s := string(p)if gregex.IsMatchString(`\[(PANI|FATA)\]`, s) {fmt.Println("SERIOUS ISSUE OCCURRED!! I'd better tell monitor in first time!")ghttp.PostContent("http://monitor.mydomain.com", s)}return w.logger.Write(p)}func main() {glog.SetWriter(&MyWriter{logger : glog.New(),})glog.Fatal("FATAL ERROR")}
执行后,输出结果为:
SERIOUS ISSUE OCCURRED!! I'd better tell monitor in first time!2019-05-23 20:14:49.374 [FATA] FATAL ERRORStack:1. /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/geg/os/glog/glog_writer_hook.go:27
使用示例2,整合graylog
假如我们需要输出日志到文件及标准输出,并且同时也需要输出日志到Graylog,很明显这个也是需要自定义Writer才能实现。当然同理,我们也可以自定义输出到其他的日志收集组件或者数据库中。
Graylog是与ELK可以相提并论的一款集中式日志管理方案,支持数据收集、检索、可视化Dashboard。
示例代码:
package mainimport ("github.com/gogf/gf/g/os/glog""github.com/robertkowalski/graylog-golang")type MyGrayLogWriter struct {gelf *gelf.Gelflogger *glog.Logger}func (w *MyGrayLogWriter) Write(p []byte) (n int, err error) {w.gelf.Send(p)return w.logger.Write(p)}func main() {glog.SetWriter(&MyGrayLogWriter{logger : glog.New(),gelf : gelf.New(gelf.Config{GraylogPort : 80,GraylogHostname : "graylog-host.com",Connection : "wan",MaxChunkSizeWan : 42,MaxChunkSizeLan : 1337,}),})glog.Println("test log")}
