Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
geata opened this issue Sep 3, 2024 · 1 comment
Open

Comments

@geata
Copy link

geata commented Sep 3, 2024

  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))
		})
	}
}
  1. it works fine in my own log
  2. but the go-zero http log like rest/handler/loghandler.go not log this added field
    how can i do?
@geata
Copy link
Author

geata commented Sep 4, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant