相关定义

可以看到第二个参数为日志处理的日志信息,并且为指针类型,意味着在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. }

使用示例

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

  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/text/gstr"
  8. )
  9. // JsonOutputsForLogger is for JSON marshaling in sequence.
  10. type JsonOutputsForLogger struct {
  11. Time string `json:"time"`
  12. Level string `json:"level"`
  13. Content string `json:"content"`
  14. }
  15. // LoggingJsonHandler is a example handler for logging JSON format content.
  16. var LoggingJsonHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) {
  17. jsonForLogger := JsonOutputsForLogger{
  18. Time: in.TimeFormat,
  19. Level: gstr.Trim(in.LevelFormat, "[]"),
  20. Content: gstr.Trim(in.Content),
  21. }
  22. jsonBytes, err := json.Marshal(jsonForLogger)
  23. if err != nil {
  24. _, _ = os.Stderr.WriteString(err.Error())
  25. return
  26. }
  27. in.Buffer.Write(jsonBytes)
  28. in.Buffer.WriteString("\n")
  29. in.Next()
  30. }
  31. func main() {
  32. g.Log().SetHandlers(LoggingJsonHandler)
  33. ctx := context.TODO()
  34. g.Log().Debug(ctx, "Debugging...")
  35. g.Log().Warning(ctx, "It is warning info")
  36. }

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

  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")