diff options
author | tjpcc <tjp@ctrl-c.club> | 2023-10-10 09:11:16 -0600 |
---|---|---|
committer | tjpcc <tjp@ctrl-c.club> | 2023-10-10 09:11:16 -0600 |
commit | d467d044798f61b34684e885cf5b1544c3fb2ee2 (patch) | |
tree | 42262014dfaaf32e559c8173b701122e2be81fef /logging | |
parent | aa15254e73d04916bead2f2743df55699987adac (diff) |
log client IPs
Diffstat (limited to 'logging')
-rw-r--r-- | logging/middleware.go | 17 |
1 files changed, 14 insertions, 3 deletions
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 { |