Go to file
Marvin Preuss 27ce2d134b
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
style: happy linting
2023-02-24 09:22:51 +00:00
vendor feat(requestid): the handler is request id aware 2023-02-24 09:07:06 +00:00
.gitignore build: uses gotestsum for testing 2022-03-23 13:44:46 +01:00
.goreleaser.yml build: adds more changelog exceptions 2022-01-20 13:09:38 +01:00
.woodpecker.yml ci: uses golang 1.18 for build process 2022-03-23 13:58:48 +01:00
go.mod feat(requestid): the handler is request id aware 2023-02-24 09:07:06 +00:00
go.sum chore: zerolog version bump 2022-03-23 13:43:18 +01:00
LICENSE adds MIT license 2021-01-18 11:20:31 +01:00
logginghandler_test.go style: happy linting 2023-02-24 09:22:51 +00:00
logginghandler.go feat(requestid): the handler is request id aware 2023-02-24 09:07:06 +00:00
Makefile build: uses gotestsum for testing 2022-03-23 13:44:46 +01:00
README.md feat!: splitting Logger function in FromRequest and FromCtx 2022-01-24 11:45:27 +01:00

logginghandler

Build Status Go Reference Go Report Card

Just a simple zerolog based request logging http middleware. It also sets a X-Request-ID in the request and response headers.

Powered by github.com/rs/zerolog/hlog and github.com/justinas/alice.

Install

go get -v go.xsfx.dev/logginghandler

Usage

logger := log.With().Logger()

handler := logginghandler.Handler(logger)(
    http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
        log := logginghander.Logger(r)
        log.Info().Msg("hello world")

        w.WriteHeader(http.StatusOK)

        return
    })
)

http.Handle("/", handler)
log.Fatal().Msg(http.ListenAndServe(":5000", nil).Error())

or with alice

logger := log.With().Logger()
chain := alice.New(logginghandler.Handler(logger)).Then(
    http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
        log := logginghander.Logger(r)
        log.Info().Msg("hello world")

        w.WriteHeader(http.StatusOK)

        return
    })
)

http.Handle("/", chain)

log.Fatal().Err(http.ListenAndServe(":5000", nil)).Msg("goodbye")

In other handlers you can access the UUID:

func anotherHandler(w http.ResponseWriter, r *http.Request) {
    log := logginghandler.FromRequest(r)

    uuid, ok := logginghandler.GetUUID(r)
    if !ok {
        log.Error().Err(err).Msg("could not find uuid")
        w.WriteHeader(http.StatusInternalServerError)

        return
    }

    fmt.Fprintf(w, "your uuid is: %s", uuid)

    return
}

The already prepared logger is also available:

l := logginghandler.FromRequest(r)
l.Info().Msg("foo bar")