diff --git a/hlog/hlog.go b/hlog/hlog.go index 37734008..e0dd512a 100644 --- a/hlog/hlog.go +++ b/hlog/hlog.go @@ -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) + }) + } +} diff --git a/hlog/hlog_test.go b/hlog/hlog_test.go index c584e98b..1f5a1bcd 100644 --- a/hlog/hlog_test.go +++ b/hlog/hlog_test.go @@ -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) + } +}