zeromicro / go-zero

A cloud-native Go microservices framework with cli tool for productivity.
https://go-zero.dev
MIT License
28.89k stars 3.91k forks source link

How to add log field in go-zero http log (rest/handler/loghandler.go) #4354

Open geata opened 1 week ago

geata commented 1 week ago
  1. add log field with http middleware

    func AddLogUserId() func(http.Handler) http.Handler {
    
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    
            ctx := r.Context()
    
            value := ctx.Value("userid")
            ctx = logx.ContextWithFields(ctx, logx.LogField{
                Key: "userid", Value: value,
            })
    
            next.ServeHTTP(w, r.WithContext(ctx))
        })
    }
    }
  2. it works fine in my own log
  3. but the go-zero http log like rest/handler/loghandler.go not log this added field how can i do?
geata commented 1 week ago

mybe there's no way... http log handler called before auth handler where userid set to ctx

func (ng *engine) bindRoute(fr featuredRoutes, router httpx.Router, metrics *stat.Metrics,
    route Route, verifier func(chain.Chain) chain.Chain) error {
    chn := ng.chain
    if chn == nil {
        chn = ng.buildChainWithNativeMiddlewares(fr, route, metrics)      // <--- http log
    }

    chn = ng.appendAuthHandler(fr, chn, verifier)                  // <--- set userid to ctx

    for _, middleware := range ng.middlewares {
        chn = chn.Append(convertMiddleware(middleware))   // <-- read from ctx then set to log filed
    }
    handle := chn.ThenFunc(route.Handler)

    return router.Handle(route.Method, route.Path, handle)
}