lasso/internal/logging/chi.go

51 lines
1.2 KiB
Go
Raw Normal View History

2021-11-12 00:13:40 +00:00
package logging
import (
"net"
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
"github.com/rs/zerolog/log"
)
func ChiLogger(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
t1 := time.Now()
defer func() {
t2 := time.Now()
// Recover and record stack traces in case of a panic
if rec := recover(); rec != nil {
log.Error().
Str("method", r.Method).
Str("path", r.URL.Path).
Msgf("Panic during request")
middleware.PrintPrettyStack(rec)
http.Error(ww, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
remoteIP, _, _ := net.SplitHostPort(r.RemoteAddr)
var event = log.Info()
if ww.Status() != 200 {
event = log.Error()
}
// log end request
event.Fields(map[string]interface{}{
"remote_ip": remoteIP,
"proto": r.Proto,
"user_agent": r.Header.Get("User-Agent"),
"status": ww.Status(),
"latency_ms": float64(t2.Sub(t1).Nanoseconds()) / 1000000.0,
}).Msgf("%s %s", r.Method, r.URL.Path)
}()
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}