all repos — website @ af7b5d9478df3da1a46e14e39fafb9fe475b0c0f

My website

use zap for logging http requests as well
Alan Pearce alan@alanpearce.eu
Sun, 19 May 2024 15:53:09 +0200
commit

af7b5d9478df3da1a46e14e39fafb9fe475b0c0f

parent

09ee2de72936ea0b0edc5d3360ce1c72803a817b

2 files changed, 9 insertions(+), 21 deletions(-)

jump to
M internal/server/logging.gointernal/server/logging.go
@@ -1,9 +1,8 @@ package server
 
 import (
-	"fmt"
-	"io"
 	"net/http"
+	"website/internal/log"
 )
 
 type loggingResponseWriter struct {
@@ -25,7 +24,6 @@ } 
 type wrappedHandlerOptions struct {
 	defaultHostname string
-	logger          io.Writer
 }
 
 func wrapHandlerWithLogging(wrappedHandler http.Handler, opts wrappedHandlerOptions) http.Handler {
@@ -41,15 +39,14 @@ } 		lw := NewLoggingResponseWriter(w)
 		wrappedHandler.ServeHTTP(lw, r)
 		statusCode := lw.statusCode
-		fmt.Fprintf(
-			opts.logger,
-			"%s %s %d %s %s %s\n",
-			scheme,
-			r.Method,
-			statusCode,
-			host,
-			r.URL.Path,
-			lw.Header().Get("Location"),
+		log.Info(
+			"http request",
+			"scheme", scheme,
+			"method", r.Method,
+			"status", statusCode,
+			"host", host,
+			"path", r.URL.Path,
+			"location", lw.Header().Get("Location"),
 		)
 	})
 }
M internal/server/server.gointernal/server/server.go
@@ -3,7 +3,6 @@ import (
 	"context"
 	"fmt"
-	"io"
 	"mime"
 	"net"
 	"net/http"
@@ -19,7 +18,6 @@ 	"github.com/getsentry/sentry-go"
 	sentryhttp "github.com/getsentry/sentry-go/http"
 	"github.com/pkg/errors"
-	"github.com/shengyanli1982/law"
 )
 
 var config *cfg.Config
@@ -168,17 +166,10 @@ newURL := runtimeConfig.BaseURL.String() + r.URL.String() 		http.Redirect(w, r, newURL, 301)
 	})
 
-	var logWriter io.Writer
-	if runtimeConfig.Production {
-		logWriter = law.NewWriteAsyncer(os.Stdout, nil)
-	} else {
-		logWriter = os.Stdout
-	}
 	top.Handle("/",
 		sentryHandler.Handle(
 			wrapHandlerWithLogging(mux, wrappedHandlerOptions{
 				defaultHostname: runtimeConfig.BaseURL.Hostname(),
-				logger:          logWriter,
 			}),
 		),
 	)