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

相关定义

Handler方法定义

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

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

Handler参数定义

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

开发者有两种方式修改默认的日志输出内容:

  • 一种是直接修改HandlerInput中的属性信息,然后继续执行in.Next()
  • 另一种自定义日志输出内容,将日志内容写入到Buffer中即可。

Handler注册到Logger方法

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

使用示例

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

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

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

  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "os"
  6. "github.com/gogf/gf/v2/frame/g"
  7. "github.com/gogf/gf/v2/os/glog"
  8. "github.com/gogf/gf/v2/text/gstr"
  9. )
  10. // JsonOutputsForLogger is for JSON marshaling in sequence.
  11. type JsonOutputsForLogger struct {
  12. Time string `json:"time"`
  13. Level string `json:"level"`
  14. Content string `json:"content"`
  15. }
  16. // LoggingJsonHandler is a example handler for logging JSON format content.
  17. var LoggingJsonHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) {
  18. jsonForLogger := JsonOutputsForLogger{
  19. Time: in.TimeFormat,
  20. Level: gstr.Trim(in.LevelFormat, "[]"),
  21. Content: gstr.Trim(in.Content),
  22. }
  23. jsonBytes, err := json.Marshal(jsonForLogger)
  24. if err != nil {
  25. _, _ = os.Stderr.WriteString(err.Error())
  26. return
  27. }
  28. in.Buffer.Write(jsonBytes)
  29. in.Buffer.WriteString("\n")
  30. in.Next(ctx)
  31. }
  32. func main() {
  33. g.Log().SetHandlers(LoggingJsonHandler)
  34. ctx := context.TODO()
  35. g.Log().Debug(ctx, "Debugging...")
  36. g.Log().Warning(ctx, "It is warning info")
  37. g.Log().Error(ctx, "Error occurs, please have a check")
  38. }

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

  1. {"time":"2021-12-31 11:03:25.438","level":"DEBU","content":"Debugging..."}
  2. {"time":"2021-12-31 11:03:25.438","level":"WARN","content":"It is warning info"}
  3. {"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客户端组件。

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/os/glog"
  6. gelf "github.com/robertkowalski/graylog-golang"
  7. )
  8. var grayLogClient = gelf.New(gelf.Config{
  9. GraylogPort: 80,
  10. GraylogHostname: "graylog-host.com",
  11. Connection: "wan",
  12. MaxChunkSizeWan: 42,
  13. MaxChunkSizeLan: 1337,
  14. })
  15. // LoggingGrayLogHandler is an example handler for logging content to remote GrayLog service.
  16. var LoggingGrayLogHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) {
  17. in.Next()
  18. grayLogClient.Log(in.Buffer.String())
  19. }
  20. func main() {
  21. g.Log().SetHandlers(LoggingGrayLogHandler)
  22. ctx := context.TODO()
  23. g.Log().Debug(ctx, "Debugging...")
  24. g.Log().Warning(ctx, "It is warning info")
  25. g.Log().Error(ctx, "Error occurs, please have a check")
  26. glog.Print(ctx, "test log")
  27. }

全局默认Handler

日志对象默认是没有设置任何的Handler,从v2.1版本开始,框架提供了可以设置全局默认Handler的功能特性。全局默认Handler将对所有的使用该日志组件,并且没有自定义Handler的日志打印功能生效。同时,全局默认Handler将会影响日志包方法的日志打印行为。

开发者可以通过以下两个方法来设置和获取全局默认的Handler

  1. // SetDefaultHandler sets default handler for package.
  2. func SetDefaultHandler(handler Handler)
  3. // GetDefaultHandler returns the default handler of package.
  4. func GetDefaultHandler() Handler

需要注意,这种全局包配置的方法不是并发安全的,并且往往需要在项目启动逻辑最顶部执行。

使用示例,我们将项目所有的日志输出均采用JSON格式输出,以保证日志内容结构化并且每次日志输出都是单行,方便日志采集期采集日志:

  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "os"
  6. "github.com/gogf/gf/v2/frame/g"
  7. "github.com/gogf/gf/v2/os/glog"
  8. "github.com/gogf/gf/v2/text/gstr"
  9. )
  10. // JsonOutputsForLogger is for JSON marshaling in sequence.
  11. type JsonOutputsForLogger struct {
  12. Time string `json:"time"`
  13. Level string `json:"level"`
  14. Content string `json:"content"`
  15. }
  16. // LoggingJsonHandler is a example handler for logging JSON format content.
  17. var LoggingJsonHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) {
  18. jsonForLogger := JsonOutputsForLogger{
  19. Time: in.TimeFormat,
  20. Level: gstr.Trim(in.LevelFormat, "[]"),
  21. Content: gstr.Trim(in.Content),
  22. }
  23. jsonBytes, err := json.Marshal(jsonForLogger)
  24. if err != nil {
  25. _, _ = os.Stderr.WriteString(err.Error())
  26. return
  27. }
  28. in.Buffer.Write(jsonBytes)
  29. in.Buffer.WriteString("\n")
  30. in.Next(ctx)
  31. }
  32. func main() {
  33. ctx := context.TODO()
  34. glog.SetDefaultHandler(LoggingJsonHandler)
  35. g.Log().Debug(ctx, "Debugging...")
  36. glog.Warning(ctx, "It is warning info")
  37. glog.Error(ctx, "Error occurs, please have a check")
  38. }

执行后,终端输出:

  1. {"time":"2022-06-20 10:51:50.235","level":"DEBU","content":"Debugging..."}
  2. {"time":"2022-06-20 10:51:50.235","level":"WARN","content":"It is warning info"}
  3. {"time":"2022-06-20 10:51:50.235","level":"ERRO","content":"Error occurs, please have a check"}

组件通用Handler

组件提供了一些常用的日志Handler,方便开发者使用,提高开发效率。

HandlerJson

Handler可以将日志内容转换为Json格式打印。使用示例:

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/os/glog"
  6. )
  7. func main() {
  8. ctx := context.TODO()
  9. glog.SetDefaultHandler(glog.HandlerJson)
  10. g.Log().Debug(ctx, "Debugging...")
  11. glog.Warning(ctx, "It is warning info")
  12. glog.Error(ctx, "Error occurs, please have a check")
  13. }

执行后,终端输出:

  1. {"Time":"2022-06-20 20:04:04.725","Level":"DEBU","Content":"Debugging..."}
  2. {"Time":"2022-06-20 20:04:04.725","Level":"WARN","Content":"It is warning info"}
  3. {"Time":"2022-06-20 20:04:04.725","Level":"ERRO","Content":"Error occurs, please have a check","Stack":"1. main.main\n /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.test/main.go:16\n"}