fix(webutils): Bad Ip logging
Fix the logging middleware only logging the last proxy's ip instead of the ip of the actual request
This commit is contained in:
parent
506834c881
commit
d7ed5b1eae
1 changed files with 26 additions and 2 deletions
|
@ -45,7 +45,7 @@ func BuildLoggingMiddleware(
|
|||
}
|
||||
logger.Send()
|
||||
}),
|
||||
hlog.RemoteAddrHandler("ip"),
|
||||
RealIpAppenderMiddleware("ip"),
|
||||
hlog.UserAgentHandler("user_agent"),
|
||||
hlog.RefererHandler("referer"),
|
||||
hlog.RequestIDHandler("req_id", "Request-Id"),
|
||||
|
@ -68,9 +68,33 @@ func LoggingMiddleware(handler http.Handler) http.Handler {
|
|||
Dur("duration", duration).
|
||||
Send()
|
||||
}),
|
||||
hlog.RemoteAddrHandler("ip"),
|
||||
RealIpAppenderMiddleware("ip"),
|
||||
hlog.UserAgentHandler("user_agent"),
|
||||
hlog.RefererHandler("referer"),
|
||||
hlog.RequestIDHandler("req_id", "Request-Id"),
|
||||
)
|
||||
}
|
||||
|
||||
// hlog.RemoteAddrHandler except fixed to check the X-Real-Ip and X-Forwarded-For
|
||||
// headers first for the IP instead of relying on RemoteAddr
|
||||
// (which would only return the last proxy's address instead of the caller's)
|
||||
func RealIpAppenderMiddleware(fieldKey string) func(handler http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
IPAddress := r.Header.Get("X-Real-Ip")
|
||||
if IPAddress == "" {
|
||||
IPAddress = r.Header.Get("X-Forwarded-For")
|
||||
}
|
||||
if IPAddress == "" {
|
||||
IPAddress = r.RemoteAddr
|
||||
}
|
||||
if IPAddress != "" {
|
||||
log := zerolog.Ctx(r.Context())
|
||||
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
|
||||
return c.Str(fieldKey, r.RemoteAddr)
|
||||
})
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue