From dd8ea20a3b8a2a6f5e353b8c813f594a8951a879 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B6=9B=E5=8F=94?= Date: Sat, 13 Jan 2024 17:16:59 +0800 Subject: [PATCH] Support logging Authorization User For reqeust with Authorization header or Proxy-Authorization header, the user name is not stored in the URL. So the logger will not output it. In order to log user name for Authorization, we could update the User filed of http.Request. So the logger should use the latest value. --- logging.go | 4 ++++ logging_test.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/logging.go b/logging.go index 2badb6f..d210783 100644 --- a/logging.go +++ b/logging.go @@ -52,6 +52,10 @@ func (h loggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { } } + if url.User != req.URL.User { + url.User = req.URL.User + } + params := LogFormatterParams{ Request: req, URL: url, diff --git a/logging_test.go b/logging_test.go index 4a89cfd..d33847a 100644 --- a/logging_test.go +++ b/logging_test.go @@ -129,6 +129,22 @@ func TestLogPathRewrites(t *testing.T) { } } +func TestLogUser(t *testing.T) { + var buf bytes.Buffer + + handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + req.URL.User = url.User("foo") + w.WriteHeader(http.StatusOK) + }) + logger := LoggingHandler(&buf, handler) + + logger.ServeHTTP(httptest.NewRecorder(), newRequest(http.MethodGet, "/")) + + if !strings.Contains(buf.String(), "- foo [") { + t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "- foo [") + } +} + func BenchmarkWriteLog(b *testing.B) { loc, err := time.LoadLocation("Europe/Warsaw") if err != nil {