Skip to content

Instantly share code, notes, and snippets.

@sttts
Created August 10, 2023 08:18
Show Gist options
  • Save sttts/741ec98599add6ae1e3764db01d16f83 to your computer and use it in GitHub Desktop.
Save sttts/741ec98599add6ae1e3764db01d16f83 to your computer and use it in GitHub Desktop.
commit dae68a69377160f6f23165064e4d6c7283981839
Author: Dr. Stefan Schimanski <[email protected]>
Date: Mon Aug 7 17:33:02 2023 +0200
gateway: add http access logs
diff --git a/cmd/gateway/main.go b/cmd/gateway/main.go
index c8f5e4df..e5c646c7 100644
--- a/cmd/gateway/main.go
+++ b/cmd/gateway/main.go
@@ -17,6 +17,7 @@ import (
chimid "github.com/go-chi/chi/v5/middleware"
"go.uber.org/zap/zapcore"
"golang.org/x/sync/errgroup"
+
"k8s.io/client-go/rest"
"k8s.io/client-go/transport"
ctrl "sigs.k8s.io/controller-runtime"
@@ -146,6 +147,7 @@ func (c *Command) runGateway(ctx context.Context, log logging.Logger) error {
gw := gateway.New(cfg, tv, gateway.WithLogger(log))
r := chi.NewRouter()
+ r.Use(logging.WithLogging(log))
r.Use(middleware.RequestID)
r.Use(chimid.Compress(5))
diff --git a/internal/logging/http.go b/internal/logging/http.go
new file mode 100644
index 00000000..0bc918ac
--- /dev/null
+++ b/internal/logging/http.go
@@ -0,0 +1,50 @@
+// Copyright 2023 Upbound Inc.
+// All rights reserved
+
+package logging
+
+import (
+ "net/http"
+ "time"
+)
+
+// WithLogging returns a middleware that logs requests.
+func WithLogging(log Logger) func(h http.Handler) http.Handler {
+ return func(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
+ start := time.Now()
+
+ resp := loggingResponseWriter{
+ ResponseWriter: rw,
+ }
+ h.ServeHTTP(&resp, req) // inject our implementation of http.ResponseWriter
+
+ log.WithValues(
+ "uri", req.RequestURI,
+ "method", req.Method,
+ "status", resp.status,
+ "duration", time.Since(start),
+ "size", resp.size,
+ "userAgent", req.UserAgent(),
+ "id", req.Header.Get("x-request-id"),
+ "srcIP", req.RemoteAddr,
+ ).Info("request completed")
+ })
+ }
+}
+
+type loggingResponseWriter struct {
+ http.ResponseWriter
+ status, size int
+}
+
+func (r *loggingResponseWriter) Write(b []byte) (int, error) {
+ size, err := r.ResponseWriter.Write(b)
+ r.size += size
+ return size, err
+}
+
+func (r *loggingResponseWriter) WriteHeader(statusCode int) {
+ r.ResponseWriter.WriteHeader(statusCode)
+ r.status = statusCode
+}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment