From d467d044798f61b34684e885cf5b1544c3fb2ee2 Mon Sep 17 00:00:00 2001 From: tjpcc Date: Tue, 10 Oct 2023 09:11:16 -0600 Subject: log client IPs --- logging/middleware.go | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) (limited to 'logging/middleware.go') diff --git a/logging/middleware.go b/logging/middleware.go index 2d0e5b9..7f4687f 100644 --- a/logging/middleware.go +++ b/logging/middleware.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "errors" "io" + "net" "time" "tildegit.org/tjp/sliderule/internal/types" @@ -15,9 +16,15 @@ func LogRequests(logger Logger) types.Middleware { return func(inner types.Handler) types.Handler { return types.HandlerFunc(func(ctx context.Context, request *types.Request) *types.Response { start := time.Now() + + var clientip string + if request.RemoteAddr != nil { + clientip, _, _ = net.SplitHostPort(request.RemoteAddr.String()) + } + response := inner.Handle(ctx, request) if response != nil { - response.Body = loggingBody(logger, request, response, start) + response.Body = loggingBody(logger, request, response, start, clientip) } else { end := time.Now() params := []any{ @@ -26,6 +33,7 @@ func LogRequests(logger Logger) types.Middleware { "dur", end.Sub(start), "url", request.URL, "status", "(not found)", + "clientip", clientip, } if fingerprint, ok := clientFingerprint(request); ok { params = append(params, "client_ident", fingerprint) @@ -52,7 +60,8 @@ type loggedResponseBody struct { response *types.Response body io.Reader - start time.Time + start time.Time + clientip string written int logger Logger @@ -66,6 +75,7 @@ func (lr *loggedResponseBody) log() { "dur", end.Sub(lr.start), "url", lr.request.URL, "status", lr.response.Status, + "clientip", lr.clientip, "bodylen", lr.written, } if fingerprint, ok := clientFingerprint(lr.request); ok { @@ -111,7 +121,7 @@ func (lwtr loggedWriteToResponseBody) WriteTo(dst io.Writer) (int64, error) { return n, err } -func loggingBody(logger Logger, request *types.Request, response *types.Response, start time.Time) io.Reader { +func loggingBody(logger Logger, request *types.Request, response *types.Response, start time.Time, clientip string) io.Reader { body := &loggedResponseBody{ request: request, response: response, @@ -119,6 +129,7 @@ func loggingBody(logger Logger, request *types.Request, response *types.Response start: start, written: 0, logger: logger, + clientip: clientip, } if _, ok := response.Body.(io.WriterTo); ok { -- cgit v1.2.3