Skip to content

Commit

Permalink
Add request logging for service bindings (#1278)
Browse files Browse the repository at this point in the history
* Add request logging for service bindings

* workflow fix

* Add message if the body is nil
  • Loading branch information
KsaweryZietara authored Oct 9, 2024
1 parent a40c8fb commit 81c35e6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/broker/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,7 @@ func createAPI(router *mux.Router, servicesConfig broker.ServicesConfig, planVal
LastBindingOperationEndpoint: broker.NewLastBindingOperation(logs),
}

router.Use(middleware.AddRequestLogging(logs))
router.Use(middleware.AddRegionToContext(cfg.DefaultRequestRegion))
router.Use(middleware.AddProviderToContext())
for _, prefix := range []string{
Expand Down
44 changes: 44 additions & 0 deletions internal/middleware/request_logging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package middleware

import (
"bytes"
"io"
"net/http"
"strings"

"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)

func AddRequestLogging(logs logrus.FieldLogger) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if strings.Contains(req.URL.Path, "service_bindings") {
logs.WithFields(logrus.Fields{
"method": req.Method,
"url": req.URL.String(),
"query": req.URL.Query(),
"headers": req.Header,
"remote_addr": req.RemoteAddr,
"host": req.Host,
"user_agent": req.UserAgent(),
}).Info("Request details")

if req.Body == nil {
logs.Info("Request body is nil")
} else {
bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
logs.Error("Failed to read request body:", err)
} else {
logs.WithField("body", string(bodyBytes)).Info("Request body")

req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
}
}
}

next.ServeHTTP(w, req)
})
}
}

0 comments on commit 81c35e6

Please sign in to comment.