caddyhttp: Optimize logs using zap's WithLazy() (#6590)

* uses zap's .WithLazy with a cloned request

* fixes the cloning

* adds comment explaining why cloning is faster
This commit is contained in:
Alexander Stecher 2024-09-26 20:23:12 +02:00 committed by GitHub
parent 2faeac0a10
commit 22c98ea165
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -313,16 +313,18 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
} }
// encode the request for logging purposes before // clone the request for logging purposes before
// it enters any handler chain; this is necessary // it enters any handler chain; this is necessary
// to capture the original request in case it gets // to capture the original request in case it gets
// modified during handling // modified during handling
// cloning the request and using .WithLazy is considerably faster
// than using .With, which will JSON encode the request immediately
shouldLogCredentials := s.Logs != nil && s.Logs.ShouldLogCredentials shouldLogCredentials := s.Logs != nil && s.Logs.ShouldLogCredentials
loggableReq := zap.Object("request", LoggableHTTPRequest{ loggableReq := zap.Object("request", LoggableHTTPRequest{
Request: r, Request: r.Clone(r.Context()),
ShouldLogCredentials: shouldLogCredentials, ShouldLogCredentials: shouldLogCredentials,
}) })
errLog := s.errorLogger.With(loggableReq) errLog := s.errorLogger.WithLazy(loggableReq)
var duration time.Duration var duration time.Duration