diff --git a/logginghandler.go b/logginghandler.go index 593a72e..8d8ff59 100644 --- a/logginghandler.go +++ b/logginghandler.go @@ -5,39 +5,42 @@ package logginghandler import ( "net/http" - "github.com/google/uuid" "github.com/rs/zerolog" - "github.com/rs/zerolog/log" + "github.com/rs/zerolog/hlog" ) // GetUUID gets the requests UUID from a request. func GetUUID(r *http.Request) string { - return r.Header.Get("X-Request-ID") + uuid, ok := hlog.IDFromRequest(r) + if !ok { + return "" + } + + return uuid.String() } // Logger returns a logger with the UUID set. func Logger(r *http.Request) zerolog.Logger { - logger := log.With().Str("uuid", GetUUID(r)).Logger() - - return logger + return *hlog.FromRequest(r) } -// Handler is the http middleware handler. -func Handler(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - uuid := uuid.New().String() - r.Header.Set("X-Request-ID", uuid) - logger := Logger(r) - logger.Info(). - Str("method", r.Method). - Str("user-agent", r.UserAgent()). - Str("proto", r.Proto). - Str("referer", r.Referer()). - Str("request-url", r.URL.String()). - Str("remote", r.RemoteAddr). - Msg("") - - w.Header().Set("X-Request-ID", uuid) - next.ServeHTTP(w, r) - }) +// Handler sets up all the logging. +func Handler(logger zerolog.Logger) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return hlog.NewHandler(logger)( + hlog.RemoteAddrHandler("remote")( + hlog.UserAgentHandler("user-agent")( + hlog.RefererHandler("referer")( + hlog.MethodHandler("method")( + hlog.RequestIDHandler("uuid", "X-Request-ID")( + hlog.URLHandler("request-url")( + next, + ), + ), + ), + ), + ), + ), + ) + } } diff --git a/logginghandler_test.go b/logginghandler_test.go index b74a67e..f33cf0b 100644 --- a/logginghandler_test.go +++ b/logginghandler_test.go @@ -12,13 +12,19 @@ import ( ) func Example() { - handler := logginghandler.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + logger := log.With().Logger() + + handler := logginghandler.Handler(logger)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + logger := logginghandler.Logger(r) + + logger.Info().Msg("this is a request") + })) + http.Handle("/", handler) log.Fatal().Msg(http.ListenAndServe(":5000", nil).Error()) } func testHandler(w http.ResponseWriter, r *http.Request) { - log.Print("got request") } func TestUUID(t *testing.T) { @@ -28,10 +34,9 @@ func TestUUID(t *testing.T) { assert.NoError(err) rr := httptest.NewRecorder() - handler := logginghandler.Handler(http.HandlerFunc(testHandler)) + handler := logginghandler.Handler(log.With().Logger())(http.HandlerFunc(testHandler)) handler.ServeHTTP(rr, req) assert.NotEmpty(rr.Header().Get("X-Request-ID")) - log.Print(rr.Header()) }