如何从中间件设置日志记录上下文? [英] How can I set up the logging context from middleware?
问题描述
我想用请求中的项目填充日志记录上下文,例如:r.Header.Get("X-Request-Id")
.我以为我可以在中间件的处理程序中覆盖Log类型.尽管它似乎不起作用,但我不确定为什么!
I want to populate the logging context by items in the request, for example: r.Header.Get("X-Request-Id")
. I assumed I could override the Log type in the handler from middleware. Though it doesn't seem to work and I am not sure why!
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)
})
}
您能看到为什么h.Log = log.WithFields(log.Fields{"test": "PASS"})
似乎对h.Log.Info("Hello from the logger")
没有任何影响的原因吗?在同一请求中应该是IIUC?
Can you see why h.Log = log.WithFields(log.Fields{"test": "PASS"})
doesn't seem to have any effect on h.Log.Info("Hello from the logger")
which should be IIUC within the same request?
推荐答案
您需要对记录程序进行请求范围的检查.每当每次建立新连接时,您都要为整个处理程序全局设置它,这意味着您要进行数据争用以及通常不受欢迎的行为.
You need your logger to be request-scoped. You're setting it globally for the entire handler, every time a new connection comes in, which means you're asking for data races, and generally undesirable behavior.
对于请求范围的上下文,嵌入在请求中的 context.Context
是完美的.您可以通过 Context()
和
For request-scoped context, the context.Context
embedded in the request is perfect. You can access it through the Context()
and WithContext
methods.
示例:
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...
}
这篇关于如何从中间件设置日志记录上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!