feat: add request-level logging

This commit is contained in:
Marc 2024-10-03 00:33:08 -04:00
parent d51031a875
commit de56bc9d0d
Signed by: marc
GPG key ID: 048E042F22B5DC79

View file

@ -3,8 +3,10 @@ package daemon
import ( import (
"context" "context"
"fmt" "fmt"
"log/slog"
"net/http" "net/http"
service "spud/service" service "spud/service"
"strconv"
) )
type Daemon struct { type Daemon struct {
@ -16,9 +18,30 @@ type Daemon struct {
type HandlerFuncWithContext = func(w http.ResponseWriter, r *http.Request, c context.Context) type HandlerFuncWithContext = func(w http.ResponseWriter, r *http.Request, c context.Context)
type RecordingResponseWriter struct {
responseWriter http.ResponseWriter
StatusCode int
}
func (r *RecordingResponseWriter) WriteHeader(statusCode int) {
r.StatusCode = statusCode
r.responseWriter.WriteHeader(statusCode)
}
func (r RecordingResponseWriter) Write(b []byte) (int, error) {
return r.responseWriter.Write(b)
}
func (r RecordingResponseWriter) Header() http.Header {
return r.responseWriter.Header()
}
func handleFuncWithContext(h HandlerFuncWithContext, c context.Context) http.HandlerFunc { func handleFuncWithContext(h HandlerFuncWithContext, c context.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
h(w, r, c) respWriter := &RecordingResponseWriter{responseWriter: w}
h(respWriter, r, c)
slog.Info("Request", "Method", r.Method, "Path", r.URL.Path, "Status", strconv.Itoa(respWriter.StatusCode))
} }
} }