整合uber-go/zap记录事件

HTTP Dispatcher只有事件的概念,事件触发后如何处理则由开发者自行决定,此处演示使用uber-go/zap这个包记录404、405、500事件:

  1. package main
  2.  
  3. import (
  4. "github.com/dxvgef/httpdispatcher"
  5. "go.uber.org/zap"
  6. "net/http"
  7. "log"
  8. )
  9.  
  10. //zap记录器的实例
  11. var Logger *zap.Logger
  12.  
  13. func main() {
  14. var dispatcher = httpdispatcher.New()
  15.  
  16. Logger, _ = zap.NewDevelopment()
  17.  
  18. //注册事件处理器
  19. dispatcher.Event.Handler = func(event *httpdispatcher.Event) {
  20. event.ResponseWriter.WriteHeader(event.Status)
  21. event.ResponseWriter.Write([]byte(event.Message))
  22. Logger.Error(
  23. event.Message.Error(),
  24. zap.Int("status", event.Status),
  25. zap.String("method", event.Request.Method),
  26. zap.String("uri", event.Request.RequestURI),
  27. zap.Strings("trace", event.Trace),
  28. )
  29. }
  30.  
  31. if err := http.ListenAndServe(":8080", dispatcher); err != nil {
  32. log.Fatal(err.Error())
  33. }
  34. }