feat(cli): add verbose logging option for CLI commands
Some checks failed
CI / build-and-test (push) Failing after -32m43s
Some checks failed
CI / build-and-test (push) Failing after -32m43s
* Introduced a new flag `--verbose` to enable detailed logging. * Implemented logging for connection events in SSE and stdio commands. * Added a utility function to handle verbose logging.
This commit is contained in:
@@ -3,12 +3,13 @@ package observability
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.warky.dev/wdevs/amcs/internal/requestip"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
@@ -67,7 +68,7 @@ func AccessLog(log *slog.Logger) func(http.Handler) http.Handler {
|
||||
slog.String("path", r.URL.Path),
|
||||
slog.Int("status", recorder.status),
|
||||
slog.Duration("duration", time.Since(started)),
|
||||
slog.String("remote_addr", stripPort(r.RemoteAddr)),
|
||||
slog.String("remote_addr", requestip.FromRequest(r)),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -100,11 +101,3 @@ func (s *statusRecorder) WriteHeader(statusCode int) {
|
||||
s.status = statusCode
|
||||
s.ResponseWriter.WriteHeader(statusCode)
|
||||
}
|
||||
|
||||
func stripPort(remote string) string {
|
||||
host, _, err := net.SplitHostPort(remote)
|
||||
if err != nil {
|
||||
return remote
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package observability
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -57,3 +59,24 @@ func TestRecoverHandlesPanic(t *testing.T) {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccessLogUsesForwardedClientIP(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
logger := slog.New(slog.NewTextHandler(&buf, nil))
|
||||
handler := AccessLog(logger)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/mcp", nil)
|
||||
req.RemoteAddr = "10.0.0.10:1234"
|
||||
req.Header.Set("X-Real-IP", "203.0.113.7")
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusNoContent)
|
||||
}
|
||||
if !strings.Contains(buf.String(), "remote_addr=203.0.113.7") {
|
||||
t.Fatalf("log output = %q, want remote_addr=203.0.113.7", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user