W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
?Writer
?接口是最底層的?IO
?寫入接口,如果業(yè)務(wù)需要自定義日志內(nèi)容打印,建議使用?Handler
?特性。
?glog
?模塊實(shí)現(xiàn)了標(biāo)準(zhǔn)輸出以及文件輸出的日志內(nèi)容打印。當(dāng)然,開發(fā)者也可以通過自定義?io.Writer
?接口實(shí)現(xiàn)自定義的日志內(nèi)容輸出。?io.Writer
?是標(biāo)準(zhǔn)庫提供的內(nèi)容輸出接口,其定義如下:
type Writer interface {
Write(p []byte) (n int, err error)
}
我們可以通過?SetWriter
?方法或者鏈?zhǔn)椒椒?To
?來實(shí)現(xiàn)自定義?Writer
?輸出,開發(fā)者可以在該?Writer
?中實(shí)現(xiàn)定義的操作,也可以在其中整合其他的模塊功能。
此外,?glog.Logger
?對(duì)象已經(jīng)實(shí)現(xiàn)了?io.Writer
?接口,因此開發(fā)者可以非常方便地將?glog
?整合使用到其他的模塊中。
在該示例中,我們實(shí)現(xiàn)了一個(gè)自定義的?Writer
?對(duì)象?MyWriter
?,在該對(duì)象實(shí)現(xiàn)的?Writer
?接口中我們對(duì)日志內(nèi)容進(jìn)行判斷,如果出現(xiàn)了?PANI
?或者?FATA
?錯(cuò)誤,那么表示是非常嚴(yán)重的錯(cuò)誤,該接口將會(huì)第一時(shí)間通過?HTTP
?接口告知?Monitor
?監(jiān)控服務(wù)。隨后再將日志內(nèi)容通過?glog
?模塊按照配置寫入到文件和標(biāo)準(zhǔn)輸出。
package main
import (
"context"
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/glog"
"github.com/gogf/gf/v2/text/gregex"
)
type MyWriter struct {
logger *glog.Logger
}
func (w *MyWriter) Write(p []byte) (n int, err error) {
var (
s = string(p)
ctx = context.Background()
)
if gregex.IsMatchString(`PANI|FATA`, s) {
fmt.Println("SERIOUS ISSUE OCCURRED!! I'd better tell monitor in first time!")
g.Client().PostContent(ctx, "http://monitor.mydomain.com", s)
}
return w.logger.Write(p)
}
func main() {
var ctx = context.Background()
glog.SetWriter(&MyWriter{
logger: glog.New(),
})
glog.Fatal(ctx, "FATAL ERROR")
}
執(zhí)行后,輸出結(jié)果為:
SERIOUS ISSUE OCCURRED!! I'd better tell monitor in first time!
2019-05-23 20:14:49.374 [FATA] FATAL ERROR
Stack:
1. /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/v2/geg/os/glog/glog_writer_hook.go:27
假如我們需要輸出日志到文件及標(biāo)準(zhǔn)輸出,并且同時(shí)也需要輸出日志到?Graylog
?,很明顯這個(gè)也是需要自定義?Writer
?才能實(shí)現(xiàn)。當(dāng)然同理,我們也可以自定義輸出到其他的日志收集組件或者數(shù)據(jù)庫中。
?Graylog
是與?ELK
可以相提并論的一款集中式日志管理方案,支持?jǐn)?shù)據(jù)收集、檢索、可視化Dashboard
?。
示例代碼:
package main
import (
"context"
"github.com/gogf/gf/v2/os/glog"
"github.com/robertkowalski/graylog-golang"
)
type MyGrayLogWriter struct {
gelf *gelf.Gelf
logger *glog.Logger
}
func (w *MyGrayLogWriter) Write(p []byte) (n int, err error) {
w.gelf.Send(p)
return w.logger.Write(p)
}
func main() {
var ctx = context.Background()
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(ctx, "test log")
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: