dougu1985 2018-12-31 04:37
浏览 73
已采纳

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

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)
    })
}

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?

  • 写回答

1条回答 默认 最新

  • doubianyan9749 2018-12-31 07:16
    关注

    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.

    For request-scoped context, the context.Context embedded in the request is perfect. You can access it through the Context() and WithContext methods.

    Example:

    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)
        })
    }
    

    Then to access your logger:

    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...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看