如何从中间件设置日志记录上下文?

时间:2018-12-31 04:37:58

标签: http go gorilla

我想用请求中的项目填充日志记录上下文,例如:r.Header.Get("X-Request-Id")。我以为我可以在中间件的处理程序中覆盖Log类型。尽管它似乎不起作用,但我不确定为什么!

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?

1 个答案:

答案 0 :(得分:1)

您需要对记录程序进行请求范围的检查。每当每次建立新连接时,您都要为整个处理程序进行全局设置,这意味着您要进行数据争用以及通常不受欢迎的行为。

对于请求范围的上下文,嵌入在请求中的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...
}