阅读(1439) (13)

GoFrame 日志组件-Handler

2022-03-29 13:54:02 更新

从​v2.0​版本开始,​glog​组件提供了超级强大的、可自定义日志处理的​Handler​特性。​Handler​采用了中间件设计方式,开发者可以为日志对象注册多个处理​Handler​,也可以在​Handler​中覆盖默认的日志组件处理逻辑。

相关定义

Handler方法定义

// Handler is function handler for custom logging content outputs.
type Handler func(ctx context.Context, in *HandlerInput)

可以看到第二个参数为日志处理的日志信息,并且为指针类型,意味着在​Handler​中可以修改该参数的任意属性信息,并且修改后的内容将会传递给下一个​Handler​。

Handler参数定义

// HandlerInput is the input parameter struct for logging Handler.
type HandlerInput struct {
	Logger       *Logger         // Logger.
	Ctx          context.Context // Context.
	Buffer       *bytes.Buffer   // Buffer for logging content outputs.
	Time         time.Time       // Logging time, which is the time that logging triggers.
	TimeFormat   string          // Formatted time string, like "2016-01-09 12:00:00".
	Color        int             // Using color, like COLOR_RED, COLOR_BLUE, etc.
	Level        int             // Using level, like LEVEL_INFO, LEVEL_ERRO, etc.
	LevelFormat  string          // Formatted level string, like "DEBU", "ERRO", etc.
	CallerFunc   string          // The source function name that calls logging.
	CallerPath   string          // The source file path and its line number that calls logging.
	CtxStr       string          // The retrieved context value string from context.
	Prefix       string          // Custom prefix string for logging content.
	Content      string          // Content is the main logging content that passed by you.
	IsAsync      bool            // IsAsync marks it is in asynchronous logging.
	handlerIndex int             // Middleware handling index for internal usage.
}

开发者有两种方式修改默认的日志输出内容:一种是直接修改​HandlerInput​中的属性信息,然后继续执行​in.Next()​;另一种自定义日志输出内容,将日志内容写入到​Buffer​中即可。

Handler注册到Logger方法

// SetHandlers sets the logging handlers for current logger.
func (l *Logger) SetHandlers(handlers ...Handler)

使用示例

我们来看两个示例便于更快速了解​Handler​的使用。

示例1. 将日志输出转换为Json格式输出

在本示例中,我们采用了前置中间件的设计,通过自定义​Handler​将日志内容输出格式修改为了​JSON​格式。

package main

import (
	"context"
	"encoding/json"
	"os"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/text/gstr"
)

// JsonOutputsForLogger is for JSON marshaling in sequence.
type JsonOutputsForLogger struct {
	Time    string `json:"time"`
	Level   string `json:"level"`
	Content string `json:"content"`
}

// LoggingJsonHandler is a example handler for logging JSON format content.
var LoggingJsonHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) {
	jsonForLogger := JsonOutputsForLogger{
		Time:    in.TimeFormat,
		Level:   gstr.Trim(in.LevelFormat, "[]"),
		Content: gstr.Trim(in.Content),
	}
	jsonBytes, err := json.Marshal(jsonForLogger)
	if err != nil {
		_, _ = os.Stderr.WriteString(err.Error())
		return
	}
	in.Buffer.Write(jsonBytes)
	in.Buffer.WriteString("\n")
	in.Next()
}

func main() {
	g.Log().SetHandlers(LoggingJsonHandler)
	ctx := context.TODO()
	g.Log().Debug(ctx, "Debugging...")
	g.Log().Warning(ctx, "It is warning info")
	g.Log().Error(ctx, "Error occurs, please have a check")
}

可以看到,我们可以在​Handler​中通过​Buffer​属性操作来控制输出的日志内容。如果在所有的前置中间件​Handler​处理后​Buffer​内容为空,那么继续​Next​执行后将会执行日志中间件默认的​Handler​逻辑。执行本示例的代码后,终端输出:

{"time":"2021-12-31 11:03:25.438","level":"DEBU","content":"Debugging..."}
{"time":"2021-12-31 11:03:25.438","level":"WARN","content":"It is warning info"}
{"time":"2021-12-31 11:03:25.438","level":"ERRO","content":"Error occurs, please have a check \nStack:\n1.  main.main\n    C:/hailaz/test/main.go:42"}

示例2. 将内容输出到第三方日志搜集服务中

在本示例中,我们采用了后置中间件的设计,通过自定义​Handler​将日志内容输出一份到第三方graylog日志搜集服务中,并且不影响原有的日志输出处理。

Graylog是与ELK可以相提并论的一款集中式日志管理方案,支持数据收集、检索、可视化Dashboard。在本示例中使用到了一个简单的第三方​graylog​客户端组件。

package main

import (
	"context"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
	gelf "github.com/robertkowalski/graylog-golang"
)

var grayLogClient = gelf.New(gelf.Config{
	GraylogPort:     80,
	GraylogHostname: "graylog-host.com",
	Connection:      "wan",
	MaxChunkSizeWan: 42,
	MaxChunkSizeLan: 1337,
})

// LoggingGrayLogHandler is an example handler for logging content to remote GrayLog service.
var LoggingGrayLogHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) {
	in.Next()
	grayLogClient.Log(in.Buffer.String())
}

func main() {
	g.Log().SetHandlers(LoggingGrayLogHandler)
	ctx := context.TODO()
	g.Log().Debug(ctx, "Debugging...")
	g.Log().Warning(ctx, "It is warning info")
	g.Log().Error(ctx, "Error occurs, please have a check")
	glog.Print(ctx, "test log")
}