You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
Go to file
Marvin Preuss 27ce2d134b
ci/woodpecker/push/woodpecker Pipeline was successful Details
ci/woodpecker/tag/woodpecker Pipeline was successful Details
style: happy linting
1 year ago
vendor feat(requestid): the handler is request id aware 1 year ago
.gitignore build: uses gotestsum for testing 2 years ago
.goreleaser.yml build: adds more changelog exceptions 2 years ago
.woodpecker.yml ci: uses golang 1.18 for build process 2 years ago
LICENSE adds MIT license 3 years ago
Makefile build: uses gotestsum for testing 2 years ago
README.md feat!: splitting Logger function in FromRequest and FromCtx 2 years ago
go.mod feat(requestid): the handler is request id aware 1 year ago
go.sum chore: zerolog version bump 2 years ago
logginghandler.go feat(requestid): the handler is request id aware 1 year ago
logginghandler_test.go style: happy linting 1 year ago

README.md

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")