40 lines
913 B
Go
40 lines
913 B
Go
package logging
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/rs/zerolog"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
type Logging struct {
|
|
log zerolog.Logger
|
|
}
|
|
|
|
func NewCLILogger() Logging {
|
|
log := log.Logger.With().Str("pkg", "middelware").Logger().Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
|
l := Logging{
|
|
log: log,
|
|
}
|
|
return l
|
|
}
|
|
|
|
func (l Logging) Middelware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
uid := uuid.NewString()
|
|
|
|
start := time.Now()
|
|
// Call the next handler
|
|
next.ServeHTTP(w, r)
|
|
elapsed := time.Since(start)
|
|
|
|
log.Info().Str("method", r.Method).Str("URI", r.URL.String()).Str("uuid", uid).Int64("request-time-ms", elapsed.Milliseconds()).Msg("Got Request")
|
|
})
|
|
}
|
|
|
|
func (l Logging) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
|
l.Middelware(next).ServeHTTP(rw, r)
|
|
}
|