Skip to content

Commit

Permalink
Support logging Authorization User
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
taoso authored and AlexVulaj committed Jan 22, 2024
1 parent 02b3ca3 commit 9c61bd8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
4 changes: 4 additions & 0 deletions logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
16 changes: 16 additions & 0 deletions logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 9c61bd8

Please sign in to comment.