From 48af0bb13214ddda31db761dcb5c2369c0f5bd5b Mon Sep 17 00:00:00 2001 From: gr-dv Date: Wed, 25 Nov 2026 15:26:32 +0300 Subject: [PATCH] Add unknown location logging with path prefix suppression --- assembly/locator.go | 7 + conf/default_remote_config.json | 3 +- conf/remote.go | 1 + middleware/entrypoint.go | 23 ++- middleware/logger.go | 5 + middleware/skip_logging.go | 33 ++++ middleware/skip_logging_test.go | 46 +++++ middleware/unknown_location.go | 26 +++ tests/unknown_locations_logging_test.go | 246 ++++++++++++++++++++++++ 9 files changed, 379 insertions(+), 11 deletions(-) create mode 100644 middleware/skip_logging.go create mode 100644 middleware/skip_logging_test.go create mode 100644 middleware/unknown_location.go create mode 100644 tests/unknown_locations_logging_test.go diff --git a/assembly/locator.go b/assembly/locator.go index 09b3da1..66ed355 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -96,6 +96,8 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha skipBodyLoggingEndpointPrefixes = append(skipBodyLoggingEndpointPrefixes, strings.TrimPrefix(prefix, "/")) } + skipLogging := middleware.NewSkipLoggingPaths(config.Logging.SkipLoggingPathPrefixes) + mux := mux2.NewRouter() for _, location := range locations { var proxyFunc middleware.Handler @@ -136,6 +138,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha middleware.Logger( l.logger, config.Logging.RequestLogEnable, enableBodyLog, + skipLogging, skipBodyLoggingEndpointPrefixes, config.Logging.EnableForceUnescapingUnicode, ), @@ -160,6 +163,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha proxyFunc, middleware.Logger(l.logger, config.Logging.RequestLogEnable, enableBodyLog, + skipLogging, skipBodyLoggingEndpointPrefixes, config.Logging.EnableForceUnescapingUnicode, ), @@ -177,6 +181,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha PathPrefix: location.PathPrefix, ErrorOnUnknownEndpoint: errorOnUnknownEndpoint, WithLendingSlash: location.Protocol != conf.GrpcProtocol, + SkipLogging: skipLogging, }, l.routes, l.logger, @@ -184,5 +189,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha mux.PathPrefix(location.PathPrefix).Handler(entrypoint) } + mux.NotFoundHandler = middleware.UnknownLocation(l.logger, skipLogging) + return mux, nil } diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index 7f0bd99..c5cd74e 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -4,7 +4,8 @@ "requestLogEnable": true, "bodyLogEnable": false, "skipBodyLoggingEndpointPrefixes": [], - "enableForceUnescapingUnicode": false + "enableForceUnescapingUnicode": false, + "skipLoggingPathPrefixes": [] }, "caching": { "authenticationDataInSec": 60, diff --git a/conf/remote.go b/conf/remote.go index c686dfe..8b15342 100644 --- a/conf/remote.go +++ b/conf/remote.go @@ -49,6 +49,7 @@ type Logging struct { BodyLogEnable bool `schema:"Включить логирование тел запросов и ответов,должно быть включено логирование запросов"` SkipBodyLoggingEndpointPrefixes []string `schema:"Выключить логирование тел запросов и ответов для путей имеющих префикс из списка,'/' в начале игнорируется"` EnableForceUnescapingUnicode bool `schema:"Включить перевод тел запроса из unicode в utf-8, должно быть включено логирование тел запросов и ответов"` + SkipLoggingPathPrefixes []string `schema:"Полностью не логировать запросы к путям с префиксом из списка (сырой path, query не учитывается, '/' в начале игнорируется). Применяется к логу запросов, предупреждению о неизвестном эндпоинте и логу незнакомых locations"` } type Caching struct { diff --git a/middleware/entrypoint.go b/middleware/entrypoint.go index 49e39f1..8fbb182 100644 --- a/middleware/entrypoint.go +++ b/middleware/entrypoint.go @@ -14,6 +14,7 @@ type EntryPointConfig struct { WithPrefix bool ErrorOnUnknownEndpoint bool WithLendingSlash bool + SkipLogging SkipLoggingPaths } type EndpointResolver interface { @@ -33,16 +34,18 @@ func Entrypoint( endpoint, err := entryPointResolver.ResolveEndpoint(req.Method, req.URL.Path, cfg) if err != nil { - lookupPath, endpoint := entryPointResolver.GetPaths(req.URL.Path, cfg) - logger.Warn( - req.Context(), - "call unknown method", - log.String("pathPrefix", cfg.PathPrefix), - log.String("httpMethod", req.Method), - log.String("originalPath", req.URL.Path), - log.String("lookupPath", lookupPath), - log.String("enpoint", endpoint), - ) + if !cfg.SkipLogging.ShouldSkip(req.URL.Path) { + lookupPath, endpoint := entryPointResolver.GetPaths(req.URL.Path, cfg) + logger.Warn( + req.Context(), + "call unknown method", + log.String("pathPrefix", cfg.PathPrefix), + log.String("httpMethod", req.Method), + log.String("originalPath", req.URL.Path), + log.String("lookupPath", lookupPath), + log.String("enpoint", endpoint), + ) + } http.Error(writer, err.Error(), http.StatusNotImplemented) return diff --git a/middleware/logger.go b/middleware/logger.go index 88de9c6..bb97517 100644 --- a/middleware/logger.go +++ b/middleware/logger.go @@ -58,6 +58,7 @@ func Logger( // nolint:gocognit,funlen logger log.Logger, enableRequestLogging bool, enableBodyLogging bool, + skipLogging SkipLoggingPaths, skipBodyLoggingEndpointPrefixes []string, enableForceUnescapingUnicode bool, ) Middleware { @@ -69,6 +70,10 @@ func Logger( // nolint:gocognit,funlen r := ctx.Request() + if skipLogging.ShouldSkip(r.URL.Path) { + return next.Handle(ctx) + } + endpoint := ctx.EndpointMeta().NormalizedEndpoint logBodyFromCurrenRequest := enableBodyLogging if logBodyFromCurrenRequest { diff --git a/middleware/skip_logging.go b/middleware/skip_logging.go new file mode 100644 index 0000000..65e0b5f --- /dev/null +++ b/middleware/skip_logging.go @@ -0,0 +1,33 @@ +package middleware + +import "strings" + +// SkipLoggingPaths — префиксы сырого request path, для которых +// полностью отключено логирование (строка лога, не только тела). +type SkipLoggingPaths struct { + prefixes []string +} + +// NewSkipLoggingPaths нормализует значения конфы: обрезает ведущий '/', +// отбрасывает пустые. +func NewSkipLoggingPaths(rawPrefixes []string) SkipLoggingPaths { + prefixes := make([]string, 0, len(rawPrefixes)) + for _, p := range rawPrefixes { + p = strings.TrimPrefix(p, "/") + if p != "" { + prefixes = append(prefixes, p) + } + } + return SkipLoggingPaths{prefixes: prefixes} +} + +// ShouldSkip — case-sensitive prefix-match. path — сырой r.URL.Path. +func (s SkipLoggingPaths) ShouldSkip(path string) bool { + path = strings.TrimPrefix(path, "/") + for _, p := range s.prefixes { + if strings.HasPrefix(path, p) { + return true + } + } + return false +} diff --git a/middleware/skip_logging_test.go b/middleware/skip_logging_test.go new file mode 100644 index 0000000..a7ae940 --- /dev/null +++ b/middleware/skip_logging_test.go @@ -0,0 +1,46 @@ +package middleware_test + +import ( + "testing" + + "isp-gate-service/middleware" + + "github.com/stretchr/testify/require" +) + +func TestSkipLoggingPaths_ShouldSkip(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + prefixes []string + path string + wantSkip bool + }{ + {name: "prefix without leading slash", prefixes: []string{"health"}, path: "/health", wantSkip: true}, + {name: "prefix with leading slash is equivalent", prefixes: []string{"/health"}, path: "/health", wantSkip: true}, + {name: "no match", prefixes: []string{"health"}, path: "/other", wantSkip: false}, + {name: "empty value is discarded", prefixes: []string{""}, path: "/health", wantSkip: false}, + {name: "root slash value is discarded", prefixes: []string{"/"}, path: "/health", wantSkip: false}, + {name: "case sensitive", prefixes: []string{"Health"}, path: "/health/x", wantSkip: false}, + {name: "plain prefix matches longer name", prefixes: []string{"health"}, path: "/healthz", wantSkip: true}, + {name: "plain prefix matches nested path", prefixes: []string{"health"}, path: "/health/x", wantSkip: true}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + matcher := middleware.NewSkipLoggingPaths(test.prefixes) + require.Equal(t, test.wantSkip, matcher.ShouldSkip(test.path)) + }) + } +} + +func TestSkipLoggingPaths_ShouldSkip_EmptyList(t *testing.T) { + t.Parallel() + + matcher := middleware.NewSkipLoggingPaths(nil) + for _, path := range []string{"/", "/health", "/health/x", "/unknown"} { + require.False(t, matcher.ShouldSkip(path)) + } +} diff --git a/middleware/unknown_location.go b/middleware/unknown_location.go new file mode 100644 index 0000000..ac8a020 --- /dev/null +++ b/middleware/unknown_location.go @@ -0,0 +1,26 @@ +package middleware + +import ( + "net/http" + + "github.com/txix-open/isp-kit/log" +) + +// UnknownLocation — catch-all для запросов, не попавших ни в один location. +func UnknownLocation(logger log.Logger, skipLogging SkipLoggingPaths) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !skipLogging.ShouldSkip(r.URL.Path) { + logger.Warn(r.Context(), "request to unknown location", + log.String("httpMethod", r.Method), + log.String("path", r.URL.Path), + log.String("remoteAddr", r.RemoteAddr), + log.String("xForwardedFor", r.Header.Get("X-Forwarded-For")), + log.String("userAgent", r.Header.Get("User-Agent")), + log.Int("statusCode", http.StatusNotFound), + ) + } + + // Ответ идентичен текущему дефолтному NotFoundHandler gorilla/mux + http.Error(w, "404 page not found", http.StatusNotFound) + }) +} diff --git a/tests/unknown_locations_logging_test.go b/tests/unknown_locations_logging_test.go new file mode 100644 index 0000000..329f67f --- /dev/null +++ b/tests/unknown_locations_logging_test.go @@ -0,0 +1,246 @@ +package tests + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "isp-gate-service/assembly" + "isp-gate-service/conf" + "isp-gate-service/routes" + + "github.com/stretchr/testify/suite" + "github.com/txix-open/isp-kit/cluster" + "github.com/txix-open/isp-kit/http/httpcli" + "github.com/txix-open/isp-kit/lb" + "github.com/txix-open/isp-kit/test" + "github.com/txix-open/isp-kit/test/httpt" + "go.uber.org/zap/zapcore" +) + +type UnknownLocationsLoggingTestSuite struct { + suite.Suite +} + +func (s *UnknownLocationsLoggingTestSuite) Test_UnknownPath_LogsWarn() { + test, require := test.New(s.T()) + capture := &logCapture{} + + locator := assembly.NewLocator(capture, nil, nil, routes.NewRoutes(test.Logger()), nil, nil, nil, nil, nil) + handler, err := locator.Handler(conf.Remote{Http: conf.Http{MaxRequestBodySizeInMb: 1}}, nil) + require.NoError(err) + + srv := httptest.NewServer(handler) + defer srv.Close() + + resp, err := httpcli.New().Get(srv.URL + "/unknown/path").Do(s.T().Context()) + require.NoError(err) + require.EqualValues(http.StatusNotFound, resp.StatusCode()) + body, err := resp.BodyCopy() + require.NoError(err) + require.EqualValues("404 page not found\n", string(body)) + + // ровно одна лог-строка на запрос, и это warn о незнакомой location + require.Len(capture.entries, 1) + entries := capture.entriesWithMessage("request to unknown location") + require.Len(entries, 1) + require.EqualValues(zapcore.WarnLevel, entries[0].level) + require.EqualValues(http.MethodGet, entries[0].fields["httpMethod"]) + require.EqualValues("/unknown/path", entries[0].fields["path"]) + require.EqualValues(http.StatusNotFound, entries[0].fields["statusCode"]) + require.NotEmpty(entries[0].fields["remoteAddr"]) +} + +func (s *UnknownLocationsLoggingTestSuite) Test_UnknownPath_SuppressionSkipsWarn() { + test, require := test.New(s.T()) + capture := &logCapture{} + + config := conf.Remote{ + Http: conf.Http{MaxRequestBodySizeInMb: 1}, + Logging: conf.Logging{SkipLoggingPathPrefixes: []string{"/unknown"}}, + } + locator := assembly.NewLocator(capture, nil, nil, routes.NewRoutes(test.Logger()), nil, nil, nil, nil, nil) + handler, err := locator.Handler(config, nil) + require.NoError(err) + + srv := httptest.NewServer(handler) + defer srv.Close() + + resp, err := httpcli.New().Get(srv.URL + "/unknown/path").Do(s.T().Context()) + require.NoError(err) + require.EqualValues(http.StatusNotFound, resp.StatusCode()) + + // запрос полностью не логируется + require.Empty(capture.entries) +} + +func (s *UnknownLocationsLoggingTestSuite) Test_UnknownEndpoint_LogsWarn() { + test, require := test.New(s.T()) + capture := &logCapture{} + + routes := routes.NewRoutes(test.Logger()) + err := routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{ + Endpoints: []cluster.EndpointDescriptor{{Path: "endpoint"}}, + }}) + require.NoError(err) + + config := conf.Remote{Http: conf.Http{MaxRequestBodySizeInMb: 1}} + locator := assembly.NewLocator(capture, nil, nil, routes, nil, nil, nil, nil, nil) + locations := []conf.Location{{ + SkipAuth: false, + PathPrefix: "/api", + Protocol: "grpc", + TargetModule: "target", + }} + handler, err := locator.Handler(config, locations) + require.NoError(err) + + srv := httptest.NewServer(handler) + defer srv.Close() + + resp, err := httpcli.New().Post(srv.URL + "/api/nope").Do(s.T().Context()) + require.NoError(err) + require.EqualValues(http.StatusNotImplemented, resp.StatusCode()) + + // ровно одна лог-строка на запрос — warn о неизвестном эндпоинте + require.Len(capture.entries, 1) + entries := capture.entriesWithMessage("call unknown method") + require.Len(entries, 1) + require.EqualValues(zapcore.WarnLevel, entries[0].level) +} + +func (s *UnknownLocationsLoggingTestSuite) Test_UnknownEndpoint_SuppressionSkipsWarn() { + test, require := test.New(s.T()) + capture := &logCapture{} + + routes := routes.NewRoutes(test.Logger()) + err := routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{ + Endpoints: []cluster.EndpointDescriptor{{Path: "endpoint"}}, + }}) + require.NoError(err) + + config := conf.Remote{ + Http: conf.Http{MaxRequestBodySizeInMb: 1}, + Logging: conf.Logging{SkipLoggingPathPrefixes: []string{"/api/nope"}}, + } + locator := assembly.NewLocator(capture, nil, nil, routes, nil, nil, nil, nil, nil) + locations := []conf.Location{{ + SkipAuth: false, + PathPrefix: "/api", + Protocol: "grpc", + TargetModule: "target", + }} + handler, err := locator.Handler(config, locations) + require.NoError(err) + + srv := httptest.NewServer(handler) + defer srv.Close() + + resp, err := httpcli.New().Post(srv.URL + "/api/nope").Do(s.T().Context()) + require.NoError(err) + require.EqualValues(http.StatusNotImplemented, resp.StatusCode()) + + require.Empty(capture.entries) +} + +func (s *UnknownLocationsLoggingTestSuite) Test_KnownEndpoint_LogsRequest() { + test, require := test.New(s.T()) + capture := &logCapture{} + + targetService := httpt.NewMock(test) + targetService.POST("/endpoint", func(ctx context.Context, httpReq *http.Request, req request) response { + return response{Id: req.Id} + }) + targetUrl, err := url.Parse(targetService.BaseURL()) + require.NoError(err) + targetHosts := map[string]*lb.RoundRobin{"target": lb.NewRoundRobin([]string{targetUrl.Host})} + + routes := routes.NewRoutes(test.Logger()) + err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{ + Endpoints: []cluster.EndpointDescriptor{{Path: "/endpoint"}}, + }}) + require.NoError(err) + + config := conf.Remote{ + Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15}, + Logging: conf.Logging{RequestLogEnable: true}, + } + locator := assembly.NewLocator(capture, nil, targetHosts, routes, nil, nil, nil, nil, nil) + locations := []conf.Location{{ + SkipAuth: true, + PathPrefix: "/api", + Protocol: "http", + TargetModule: "target", + }} + handler, err := locator.Handler(config, locations) + require.NoError(err) + + srv := httptest.NewServer(handler) + defer srv.Close() + + resp, err := httpcli.New().Post(srv.URL + "/api/endpoint"). + JsonRequestBody(request{Id: "test"}). + Do(s.T().Context()) + require.NoError(err) + require.EqualValues(http.StatusOK, resp.StatusCode()) + + // ровно одна лог-строка на запрос — log request + require.Len(capture.entries, 1) + entries := capture.entriesWithMessage("log request") + require.Len(entries, 1) + require.EqualValues("/api/endpoint", entries[0].fields["path"]) +} + +func (s *UnknownLocationsLoggingTestSuite) Test_KnownEndpoint_SuppressionSkipsRequestLog() { + test, require := test.New(s.T()) + capture := &logCapture{} + + targetService := httpt.NewMock(test) + targetService.POST("/endpoint", func(ctx context.Context, httpReq *http.Request, req request) response { + return response{Id: req.Id} + }) + targetUrl, err := url.Parse(targetService.BaseURL()) + require.NoError(err) + targetHosts := map[string]*lb.RoundRobin{"target": lb.NewRoundRobin([]string{targetUrl.Host})} + + routes := routes.NewRoutes(test.Logger()) + err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{ + Endpoints: []cluster.EndpointDescriptor{{Path: "/endpoint"}}, + }}) + require.NoError(err) + + config := conf.Remote{ + Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15}, + Logging: conf.Logging{ + RequestLogEnable: true, + SkipLoggingPathPrefixes: []string{"/api/endpoint"}, + }, + } + locator := assembly.NewLocator(capture, nil, targetHosts, routes, nil, nil, nil, nil, nil) + locations := []conf.Location{{ + SkipAuth: true, + PathPrefix: "/api", + Protocol: "http", + TargetModule: "target", + }} + handler, err := locator.Handler(config, locations) + require.NoError(err) + + srv := httptest.NewServer(handler) + defer srv.Close() + + resp, err := httpcli.New().Post(srv.URL + "/api/endpoint"). + JsonRequestBody(request{Id: "test"}). + Do(s.T().Context()) + require.NoError(err) + require.EqualValues(http.StatusOK, resp.StatusCode()) + + require.Empty(capture.entries) +} + +func TestUnknownLocationsLoggingTestSuite(t *testing.T) { + t.Parallel() + suite.Run(t, new(UnknownLocationsLoggingTestSuite)) +}