Skip to content

Commit

Permalink
hlog: add HostHandler (#604)
Browse files Browse the repository at this point in the history
  • Loading branch information
michiomochi authored Oct 20, 2023
1 parent 6ed7439 commit 2c1cbec
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions hlog/hlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,3 +216,17 @@ func AccessHandler(f func(r *http.Request, status, size int, duration time.Durat
})
}
}

// HostHandler adds the request's host as a field to the context's logger
// using fieldKey as field key.
func HostHandler(fieldKey string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := zerolog.Ctx(r.Context())
log.UpdateContext(func(c zerolog.Context) zerolog.Context {
return c.Str(fieldKey, r.Host)
})
next.ServeHTTP(w, r)
})
}
}
14 changes: 14 additions & 0 deletions hlog/hlog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,17 @@ func TestCtxWithID(t *testing.T) {
t.Errorf("CtxWithID() = %v, want %v", got, want)
}
}

func TestHostHandler(t *testing.T) {
out := &bytes.Buffer{}
r := &http.Request{Host: "example.com"}
h := HostHandler("host")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
l := FromRequest(r)
l.Log().Msg("")
}))
h = NewHandler(zerolog.New(out))(h)
h.ServeHTTP(nil, r)
if want, got := `{"host":"example.com"}`+"\n", decodeIfBinary(out); want != got {
t.Errorf("Invalid log output, got: %s, want: %s", got, want)
}
}

0 comments on commit 2c1cbec

Please sign in to comment.