go-chi / httplog

Go HTTP request logger with structured logging capabilities built on "log/slog" package
MIT License
207 stars 42 forks source link

Allow excluding endpoints or path patterns from logging #11

Closed Goldziher closed 1 year ago

Goldziher commented 2 years ago

Hi people,

So this is a feature request, and I'd be happy to submit a PR for it if it's deemed ok. In my use case I'd like to exclude some endpoints from being logged, e.g. the "healthz" and "readyz" endpoints used by k8, which are completely useless to me in terms of logging.

pkieltyka commented 2 years ago

@Goldziher definitely -- I do this as well.. you have a few options

  1. Use middleware.Heartbeat from chi and register it before the logger, so it will respond before it even hits the logger
  2. See middleware.Maybe inside of chi
Goldziher commented 2 years ago

Thanks! i am using the heartbeat middleware now:


// CreateChiMux creates an instance of chi.Mux, settings the api routers and all the middlewares.
func CreateChiMux(logger zerolog.Logger, handlers ...middleware.MiddlewareHandler) *chi.Mux {
    middlewares := []func(next http.Handler) http.Handler{
        chiMiddleware.Timeout(time.Second * 15),
        // heartbeat middleware must go before logging, to ensure these endpoints do not spam the logs with health checks
        chiMiddleware.Heartbeat("/healthz"),
        chiMiddleware.Heartbeat("/readyz"),
        // the httplog.RequestLogger middleware should go before the other middlewares to catch panics and exceptions.
        // note - it also sets the chi RequestId and Recoverer middlewares, so these are also in effect included here.
        httplog.RequestLogger(logger),
    }

    for _, handler := range handlers {
        middlewares = append(middlewares, handler)
    }

    return router.New(middlewares...)
}
swade1987 commented 2 years ago
MiddlewareHandler

I tried this but now when I hit /healthz or /metrics my response is just . every time.

pkieltyka commented 1 year ago

done in v2