summaryrefslogtreecommitdiff
path: root/server/middleware/logging.go
diff options
context:
space:
mode:
authorMichael Hunteman <huntemanmt@gmail.com>2025-01-31 12:32:09 -0600
committerMichael Hunteman <huntemanmt@gmail.com>2025-01-31 12:32:09 -0600
commit6150d079ea06ba55e5f145b67f02065d94b757f9 (patch)
treed8994e3793fc55e052c7d7a780112b323128de13 /server/middleware/logging.go
parentff05f3941721de3ff343421968422d216d82e952 (diff)
Improve logging and error handling
Diffstat (limited to 'server/middleware/logging.go')
-rw-r--r--server/middleware/logging.go34
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)))
}
})
}