我想通过请求中的项目填充日志记录上下文,例如:r.Header.Get("X-Request- Id")。我以为我可以在中间件的处理程序中覆盖Log类型。虽然它似乎不起作用,但我不确定为什么!
r.Header.Get("X-Request- Id")
package main import ( "fmt" "net/http" "os" "github.com/apex/log" "github.com/gorilla/mux" ) // Assumption: handler is the shared state between the functions type handler struct{ Log *log.Entry } // New creates a handler for this application to co-ordinate shared resources func New() (h handler) { return handler{Log: log.WithFields(log.Fields{"test": "FAIL"})} } func (h handler) index(w http.ResponseWriter, r *http.Request) { h.Log.Info("Hello from the logger") fmt.Fprint(w, "YO") } func main() { h := New() app := mux.NewRouter() app.HandleFunc("/", h.index) app.Use(h.loggingMiddleware) if err := http.ListenAndServe(":"+os.Getenv("PORT"), app); err != nil { log.WithError(err).Fatal("error listening") } } func (h handler) loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.Log = log.WithFields(log.Fields{"test": "PASS"}) next.ServeHTTP(w, r) }) }
您能看到为什么在同一请求中对IIUC应该h.Log = log.WithFields(log.Fields{"test": "PASS"})没有影响h.Log.Info("Hello from the logger")吗?
h.Log = log.WithFields(log.Fields{"test": "PASS"})
h.Log.Info("Hello from the logger")
您需要对记录程序进行请求范围的检查。每当有新的连接进入时,就为整个处理程序全局设置它,这意味着您要进行数据争用以及通常不受欢迎的行为。
对于请求范围的上下文,请求中的context.Context嵌入是完美的。您可以通过Context()和WithContext方法访问它。
context.Context
Context()
WithContext
例:
var loggerKey = "Some unique key" func (h handler) loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() ctx = context.WithValue(ctx, loggerKey, log.WithFields(log.Fields{"test": "PASS"})) next.ServeHTTP(w, r.WithContext(ctx) }) }
然后访问记录器:
func doSomething(r *http.Request) error { log, ok := r.Context().Value(loggerKey).(*log.Logger) // Or whatever type is appropriate if !ok { return errors.New("logger not set on context!") } // Do stuff... }