created hws module
This commit is contained in:
38
hws/middleware_logging.go
Normal file
38
hws/middleware_logging.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package hws
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Middleware to add logs to console with details of the request
|
||||
func logging(next http.Handler, logger *logger) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if logger == nil {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if slices.Contains(logger.ignoredPaths, r.URL.Path) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
start, err := getStartTime(r.Context())
|
||||
if err != nil {
|
||||
logger.logger.Error().Err(err)
|
||||
return
|
||||
}
|
||||
wrapped := &wrappedWriter{
|
||||
ResponseWriter: w,
|
||||
statusCode: http.StatusOK,
|
||||
}
|
||||
next.ServeHTTP(wrapped, r)
|
||||
logger.logger.Info().
|
||||
Int("status", wrapped.statusCode).
|
||||
Str("method", r.Method).
|
||||
Str("resource", r.URL.Path).
|
||||
Dur("time_elapsed", time.Since(start)).
|
||||
Str("remote_addr", r.Header.Get("X-Forwarded-For")).
|
||||
Msg("Served")
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user