diff options
Diffstat (limited to 'server/middleware/logging.go')
-rw-r--r-- | server/middleware/logging.go | 34 |
1 files changed, 17 insertions, 17 deletions
diff --git a/server/middleware/logging.go b/server/middleware/logging.go index 860a467..d91a5c8 100644 --- a/server/middleware/logging.go +++ b/server/middleware/logging.go @@ -2,8 +2,10 @@ package middleware import ( "bytes" - "log" + "fmt" + "log/slog" "net/http" + "os" "time" ) @@ -18,33 +20,31 @@ func (w *LoggingResponseWriter) WriteHeader(code int) { w.ResponseWriter.WriteHeader(code) } -func (w *LoggingResponseWriter) Write(data []byte) (int, error) { - w.responseBody.Write(data) - return w.ResponseWriter.Write(data) +func (w *LoggingResponseWriter) Write(b []byte) (int, error) { + w.responseBody.Write(b) + return w.ResponseWriter.Write(b) } func LoggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() - loggingWriter := &LoggingResponseWriter{ + rw := &LoggingResponseWriter{ ResponseWriter: w, statusCode: http.StatusOK, responseBody: &bytes.Buffer{}, } - next.ServeHTTP(loggingWriter, r) - - log.Printf( - "Client IP: %s | Method: %s | Path: %s | Status: %d | Duration: %v", - r.RemoteAddr, - r.Method, - r.URL.Path, - loggingWriter.statusCode, - time.Since(start), - ) - if loggingWriter.responseBody.Len() > 0 { - log.Print(loggingWriter.responseBody.String()) + jsonHandler := slog.NewJSONHandler(os.Stderr, nil) + myslog := slog.New(jsonHandler) + next.ServeHTTP(rw, r) + + if rw.statusCode >= 400 { + myslog.Error("Request", "IP", r.RemoteAddr, "Method", r.Method, "Path", r.URL.Path, "Status", + rw.statusCode, "Duration", fmt.Sprint(time.Since(start)), "Response", rw.responseBody.String()) + } else { + myslog.Info("Request", "IP", r.RemoteAddr, "Method", r.Method, "Path", r.URL.Path, "Status", + rw.statusCode, "Duration", fmt.Sprint(time.Since(start))) } }) } |