整合uber-go/zap记录事件
HTTP Dispatcher只有事件的概念,事件触发后如何处理则由开发者自行决定,此处演示使用uber-go/zap
这个包记录404、405、500
事件:
- package main
- import (
- "github.com/dxvgef/httpdispatcher"
- "go.uber.org/zap"
- "net/http"
- "log"
- )
- //zap记录器的实例
- var Logger *zap.Logger
- func main() {
- var dispatcher = httpdispatcher.New()
- Logger, _ = zap.NewDevelopment()
- //注册事件处理器
- dispatcher.Event.Handler = func(event *httpdispatcher.Event) {
- event.ResponseWriter.WriteHeader(event.Status)
- event.ResponseWriter.Write([]byte(event.Message))
- Logger.Error(
- event.Message.Error(),
- zap.Int("status", event.Status),
- zap.String("method", event.Request.Method),
- zap.String("uri", event.Request.RequestURI),
- zap.Strings("trace", event.Trace),
- )
- }
- if err := http.ListenAndServe(":8080", dispatcher); err != nil {
- log.Fatal(err.Error())
- }
- }