From 76752b4489cd05e154a02f5d3d5a40d3e24d4cf9 Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Sat, 21 Nov 2026 16:59:43 +0000 Subject: [PATCH 1/2] feature: debug logging opt-in closes #752 --- .gitignore | 2 ++ config.default.ini | 33 +++++++++++++++++++ src/Application.php | 10 ++++++ src/Debug/DebugLogger.php | 17 ++++++++++ src/Dispatch/Dispatcher.php | 24 ++++++++++++++ src/Init/ViewModelInit.php | 3 ++ src/Logic/HTMLDocumentProcessor.php | 18 +++++++--- src/Logic/LogicExecutor.php | 5 +++ src/Logic/ViewModelProcessor.php | 7 +++- src/Service/ContainerFactory.php | 5 +++ .../Logic/HTMLDocumentProcessorTest.php | 19 +++++++++-- 11 files changed, 136 insertions(+), 7 deletions(-) create mode 100644 src/Debug/DebugLogger.php diff --git a/.gitignore b/.gitignore index 3d5422a0..6bdd11f3 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ /test/behaviour/project/*/vendor /test/phpunit/.phpunit.cache .phpunit*.cache + +config.*.ini diff --git a/config.default.ini b/config.default.ini index 79a6ea36..5153012c 100644 --- a/config.default.ini +++ b/config.default.ini @@ -31,6 +31,23 @@ component_directory=page/_component partial_directory=page/_partial [logger] +; Opt-in DEBUG diagnostics (also require level=debug for the destination). +; HTML component expansion and optional PHP logic files. +debug_html_components=false +; Partial expansion and missing partial directories. +debug_html_partials=false +; Request start, redirects, completion and error handling. +debug_requests=false +; Path normalisation, route selection and matched view/logic files. +debug_routing=false +; Logic lifecycle phases and completed function calls. +debug_logic=false +; View preparation and streaming. +debug_views=false +; CSRF verification decisions (never token values). +debug_csrf=false +; Service loader selection and fallback. +debug_services=false log_all_requests=true log_static_requests=false log_404_to_error_log=false @@ -90,3 +107,19 @@ csrf_max_tokens=100 csrf_token_length=32 ;Generate tokens once "per-form" or once "per-page" csrf_token_sharing=per-form + +[deploy] +; Deployment server; HTTPS is assumed when no scheme is supplied. +server=deploy.php.gt +; Deployment transport; currently only tar-http is supported. +transport=tar-http +; Private token and its issuing server, saved by gt deploy in config.dev.ini. +token= +token_server= + +[deployment] +; Private environment tokens, generated in config.dev.ini by gt deploy. +staging_token= +staging_token_server= +production_token= +production_token_server= diff --git a/src/Application.php b/src/Application.php index 40988f7b..95066e38 100644 --- a/src/Application.php +++ b/src/Application.php @@ -6,6 +6,7 @@ use GT\Http\ResponseStatusException\ClientError\ClientErrorException; use GT\Http\ResponseStatusException\ResponseStatusException; use GT\Logger\Log; +use GT\WebEngine\Debug\DebugLogger; use GT\Logger\LogConfig; use GT\Logger\LogHandler\StdErrHandler; use GT\Logger\LogLevel; @@ -45,6 +46,7 @@ * @SuppressWarnings("PHPMD.ExcessiveClassComplexity") */ class Application { + private DebugLogger $debugLogger; private const string REDACTED_LOG_VALUE = "[redacted]"; private Redirect $redirect; @@ -80,6 +82,7 @@ public function __construct( ?Protection $globalProtection = null, ) { $this->initConfig($config); + $this->debugLogger = new DebugLogger($this->config); $this->configureLoggerStreams(); $this->redirect = $this->createRedirect($redirect); $application = $this; @@ -111,9 +114,11 @@ public function __construct( public function start():void { // Before we start, we check if the current URI should be redirected. If it // should, we won't go any further into the lifecycle. + $this->debugLogger->log("requests", "Request lifecycle started"); $requestedPath = $this->getRequestedPath(); $redirectUri = $this->redirect->execute($requestedPath); if($redirectUri) { + $this->debugLogger->log("requests", "Redirect rule matched", ["status" => $redirectUri->code]); $this->logRedirect($redirectUri, $requestedPath); return; } @@ -193,6 +198,7 @@ private function createRedirect(?Redirect $redirect = null):Redirect { } private function handleThrowable(Throwable $throwable):?Response { + $this->debugLogger->log("requests", "Handling request exception", ["exception" => get_class($throwable)]); $this->sentryReporter?->report($throwable); if ($errorScript = $this->config->getString('app.error_script')) { $this->restoreGlobals(); @@ -270,6 +276,10 @@ private function finish( $this->timer->stop(); $this->timer->logDelta(); + $this->debugLogger->log("requests", "Request lifecycle completed", [ + "status" => $response->getStatusCode(), + "seconds" => $this->timer->getDelta(), + ]); $this->sentryLogHandler?->flush(); } diff --git a/src/Debug/DebugLogger.php b/src/Debug/DebugLogger.php new file mode 100644 index 00000000..187dd2e6 --- /dev/null +++ b/src/Debug/DebugLogger.php @@ -0,0 +1,17 @@ + $context */ + public function log(string $category, string $message, array $context = []):void { + if(filter_var($this->config?->getString("logger.debug_" . $category), FILTER_VALIDATE_BOOLEAN)) { + Log::debug($message, $context); + } + } +} diff --git a/src/Dispatch/Dispatcher.php b/src/Dispatch/Dispatcher.php index a775b0b4..d502f973 100644 --- a/src/Dispatch/Dispatcher.php +++ b/src/Dispatch/Dispatcher.php @@ -29,6 +29,7 @@ use GT\Input\InputData\InputData; use GT\Json\Schema\JSONDocument; use GT\Logger\Log; +use GT\WebEngine\Debug\DebugLogger; use GT\Routing\Assembly; use GT\Routing\BaseRouter; use GT\Routing\Path\DynamicPath; @@ -56,6 +57,7 @@ * @SuppressWarnings("PHPMD.ExcessiveClassComplexity") */ class Dispatcher { + private DebugLogger $debugLogger; private const LOGIC_EXECUTION_HEADER = "X-Logic-Execution"; private const COMPONENT_INPUT_NAME = "__component"; @@ -117,6 +119,7 @@ public function __construct( // Set the first Dispatcher dependencies - these are required to be passed from // the Application, so come first as non-nullable: $this->config = $config; + $this->debugLogger = new DebugLogger($this->config); $this->request = $request; $this->globals = $globals; $this->finishCallback = $finishCallback; @@ -159,10 +162,12 @@ public function __construct( $this->globals["_FILES"], $this->globals["_SERVER"], ); + $this->debugLogger->log("routing", "Request path normalisation completed"); $this->input = $requestInit->getInput(); $this->serviceContainer->set($this->input); $this->serviceContainer->set($requestInit->getServerInfo()); if($this->isRedirectPrepared()) { + $this->debugLogger->log("routing", "Path normalisation prepared a redirect"); $this->redirectPrepared = true; return; } @@ -191,6 +196,12 @@ public function __construct( $this->serviceContainer->set($dynamicPath); $this->viewAssembly = $routerInit->getViewAssembly(); $this->logicAssembly = $routerInit->getLogicAssembly(); + $this->debugLogger->log("routing", "Route selected", [ + "router" => get_class($this->router), + "view" => get_class($this->view), + "view_files" => iterator_to_array(clone $this->viewAssembly), + "logic_files" => iterator_to_array(clone $this->logicAssembly), + ]); $sessionInit = $sessionInit ?? new SessionInit( $this->config->getString("session.name"), @@ -215,6 +226,7 @@ public function __construct( $this->viewModel, $this->config->getString("view.component_directory"), $this->config->getString("view.partial_directory"), + $this->debugLogger, ); $this->viewModelProcessor = $viewModelInit->getViewModelProcessor(); $this->viewInitCb = $this->viewModel instanceof HTMLDocument @@ -238,6 +250,7 @@ public function __construct( $this->logicExecutor = $logicExecutor ?? new LogicExecutor( $appNamespace, $this->injector, + $this->debugLogger, ); $this->viewStreamer = $viewStreamer ?? new ViewStreamer(); $this->headerManager = $headerManager ?? new HeaderManager(); @@ -256,6 +269,7 @@ public function generateResponse():Response { // step individually to ensure proper error handling throughout the process. if(!$this->viewAssembly->containsDistinctFile() && !$this->logicAssembly->containsDistinctFile()) { $this->response = $this->response->withStatus(StatusCode::NOT_FOUND); + $this->debugLogger->log("routing", "No distinct view or logic file matched"); throw new HttpNotFound(); } @@ -517,7 +531,9 @@ private function setupJsonDocumentErrorCallback():void { ); } + $this->debugLogger->log("views", "Streaming prepared view", ["view" => get_class($this->view)]); $this->viewStreamer->stream($this->view, $this->viewModel); + $this->debugLogger->log("views", "View streaming completed"); ($this->finishCallback)($this->response); if($this->interruptResponse) { @@ -531,6 +547,7 @@ private function handleLogicExecution( Input $input, ?Element $component = null, ):void { + $this->debugLogger->log("logic", "Starting logic lifecycle", ["component" => $component?->tagName]); $extraArgs = []; if($component) { @@ -668,10 +685,13 @@ public function processResponse( $this->applyResponseHeaders(); $this->prepareViewModelForStreaming(); + $this->debugLogger->log("views", "Streaming prepared view", ["view" => get_class($this->view)]); $this->viewStreamer->stream($this->view, $this->viewModel); + $this->debugLogger->log("views", "View streaming completed"); $this->consumeCsrfToken($csrfToken); } catch(ResponseInterrupt) { + $this->debugLogger->log("logic", "Response interrupted by logic"); $this->consumeCsrfToken($csrfToken); return; } @@ -716,6 +736,7 @@ private function prepareViewModelForStreaming():void { private function recordLogicExecution(string $functionReference):void { $refWithoutAttributes = explode("#", $functionReference, 2)[0]; + $this->debugLogger->log("logic", "Logic function completed", ["function" => $refWithoutAttributes]); $separatorPosition = strrpos($refWithoutAttributes, "::"); if($separatorPosition === false) { return; @@ -750,10 +771,12 @@ private function normaliseLogicExecutionFile(string $file):string { private function verifyCsrfRequest(string $method, InputData $inputData):?string { if(!($this->viewModel instanceof HTMLDocument)) { + $this->debugLogger->log("csrf", "CSRF verification skipped for non-HTML response"); return null; } if($method !== "POST" || $this->isIgnoredCsrfPath()) { + $this->debugLogger->log("csrf", "CSRF verification skipped for method or ignored path"); return null; } @@ -771,6 +794,7 @@ private function verifyCsrfRequest(string $method, InputData $inputData):?string $token = $postData[HTMLDocumentProtector::TOKEN_NAME]; $tokenStore->verifyToken($token); + $this->debugLogger->log("csrf", "CSRF verification succeeded"); return $token; } catch(CsrfException $exception) { diff --git a/src/Init/ViewModelInit.php b/src/Init/ViewModelInit.php index 11c0e945..22799142 100644 --- a/src/Init/ViewModelInit.php +++ b/src/Init/ViewModelInit.php @@ -2,6 +2,7 @@ namespace GT\WebEngine\Init; use GT\Dom\HTMLDocument; +use GT\WebEngine\Debug\DebugLogger; use GT\DomTemplate\BindableCache; use GT\DomTemplate\DocumentBinder; use GT\DomTemplate\ElementBinder; @@ -23,11 +24,13 @@ public function __construct( HTMLDocument|JSONDocument $model, string $componentDirectory, string $partialDirectory, + ?DebugLogger $debugLogger = null, ) { if($model instanceof HTMLDocument) { $this->viewModelProcessor = new HTMLDocumentProcessor( $componentDirectory, $partialDirectory, + $debugLogger, ); } // TODO: Handle other view model types. diff --git a/src/Logic/HTMLDocumentProcessor.php b/src/Logic/HTMLDocumentProcessor.php index 9a61760f..b8c11ef9 100644 --- a/src/Logic/HTMLDocumentProcessor.php +++ b/src/Logic/HTMLDocumentProcessor.php @@ -6,7 +6,6 @@ use GT\DomTemplate\PartialContent; use GT\DomTemplate\PartialContentDirectoryNotFoundException; use GT\DomTemplate\PartialExpander; -use GT\Logger\Log; use GT\Routing\Assembly; use GT\Routing\Path\DynamicPath; use GT\WebEngine\View\HeaderFooterPartialConflictException; @@ -63,8 +62,13 @@ function processPartialContent( $partial, ); $partialExpander->expand(); + $this->debugLogger->log("html_partials", "HTML partial expansion completed"); + } + catch(PartialContentDirectoryNotFoundException) { + $this->debugLogger->log("html_partials", "HTML partial directory not found", [ + "directory" => $this->partialDirectory, + ]); } - catch(PartialContentDirectoryNotFoundException) {} try { // TODO: Handle other model types in sub-functions. @@ -84,7 +88,8 @@ function processPartialContent( $filePath .= ".php"; if(!is_file($filePath)) { - Log::debug( + $this->debugLogger->log( + "html_components", "Component detected without matching logic file", [ "component" => strtolower($componentElement->tagName), @@ -94,6 +99,7 @@ function processPartialContent( continue; } + $this->debugLogger->log("html_components", "Component logic file found", ["logic_file" => $filePath]); $componentAssembly = new Assembly(); $componentAssembly->add($filePath); $componentList->addAssemblyComponent( @@ -102,7 +108,11 @@ function processPartialContent( ); } } - catch(PartialContentDirectoryNotFoundException) {} + catch(PartialContentDirectoryNotFoundException) { + $this->debugLogger->log("html_components", "HTML component directory not found", [ + "directory" => $this->componentDirectory, + ]); + } return $componentList; } diff --git a/src/Logic/LogicExecutor.php b/src/Logic/LogicExecutor.php index 0ceed620..415179ae 100644 --- a/src/Logic/LogicExecutor.php +++ b/src/Logic/LogicExecutor.php @@ -2,6 +2,7 @@ namespace GT\WebEngine\Logic; use Generator; +use GT\WebEngine\Debug\DebugLogger; use GT\Routing\Assembly; use GT\Routing\LogicStream\LogicStreamNamespace; use GT\Routing\LogicStream\LogicStreamWrapper; @@ -12,6 +13,7 @@ class LogicExecutor { public function __construct( private string $appNamespace, private Injector $injector, + private ?DebugLogger $debugLogger = null, ) { } @@ -23,6 +25,7 @@ public function __construct( // phpcs:disable Generic.Metrics.NestingLevel.TooHigh public function invoke(Assembly $logicAssembly, string $name, array $extraArgs = []):Generator { foreach($logicAssembly as $file) { + $this->debugLogger?->log("logic", "Loading logic file", ["file" => $file]); $this->loadLogicFile($file); } @@ -43,6 +46,7 @@ public function invoke(Assembly $logicAssembly, string $name, array $extraArgs = if($instance) { if(method_exists($instance, $name)) { + $this->debugLogger?->log("logic", "Invoking logic method", ["file" => $file, "method" => $name]); $this->injector->invoke( $instance, $name, @@ -61,6 +65,7 @@ public function invoke(Assembly $logicAssembly, string $name, array $extraArgs = foreach($fnReferenceArray as $fnReference) { if(function_exists($fnReference)) { + $this->debugLogger?->log("logic", "Invoking logic function", ["file" => $file, "function" => $name]); $refFunction = new ReflectionFunction($fnReference); foreach($refFunction->getAttributes() as $refAttr) { $functionReference .= "#"; diff --git a/src/Logic/ViewModelProcessor.php b/src/Logic/ViewModelProcessor.php index 28a85d01..6eddb13e 100644 --- a/src/Logic/ViewModelProcessor.php +++ b/src/Logic/ViewModelProcessor.php @@ -2,14 +2,19 @@ namespace GT\WebEngine\Logic; use GT\Dom\HTMLDocument; +use GT\WebEngine\Debug\DebugLogger; use GT\Routing\Assembly; use GT\Routing\Path\DynamicPath; abstract class ViewModelProcessor { + protected DebugLogger $debugLogger; public function __construct( protected string $componentDirectory, protected string $partialDirectory, - ) {} + ?DebugLogger $debugLogger = null, + ) { + $this->debugLogger = $debugLogger ?? new DebugLogger(); + } abstract function processDynamicPath( HTMLDocument $model, diff --git a/src/Service/ContainerFactory.php b/src/Service/ContainerFactory.php index 2cf1a21b..649bd3bb 100644 --- a/src/Service/ContainerFactory.php +++ b/src/Service/ContainerFactory.php @@ -2,22 +2,27 @@ namespace GT\WebEngine\Service; use GT\Config\Config; +use GT\WebEngine\Debug\DebugLogger; use GT\ServiceContainer\Container; class ContainerFactory { public function create(Config $config):Container { + $debug = new DebugLogger($config); $container = new Container(); $registered = false; foreach($this->getLoaderClassNames($config) as $loaderClass) { if(!class_exists($loaderClass)) { + $debug->log("services", "Service loader class not found", ["class" => $loaderClass]); continue; } $container->addLoaderClass(new $loaderClass($config, $container)); + $debug->log("services", "Service loader registered", ["class" => $loaderClass]); $registered = true; } if(!$registered) { + $debug->log("services", "Using default service loader"); $container->addLoaderClass(new DefaultServiceLoader($config, $container)); } diff --git a/test/phpunit/Logic/HTMLDocumentProcessorTest.php b/test/phpunit/Logic/HTMLDocumentProcessorTest.php index 05c296d0..1ee6ec61 100644 --- a/test/phpunit/Logic/HTMLDocumentProcessorTest.php +++ b/test/phpunit/Logic/HTMLDocumentProcessorTest.php @@ -4,6 +4,10 @@ require_once __DIR__ . "/../Fixture/TestLogHandler.php"; use GT\WebEngine\Logic\HTMLDocumentProcessor; +use GT\Config\Config; +use GT\Config\ConfigSection; +use GT\WebEngine\Debug\DebugLogger; +use PHPUnit\Framework\Attributes\DataProvider; use GT\Dom\Element; use GT\Dom\HTMLDocument; use GT\Logger\LogConfig; @@ -58,7 +62,12 @@ public function testProcessDynamicPath_addsUriDirectoryAndDynamicClasses():void self::assertContains("_item--macbook-pro", $classes); } - public function testProcessPartialContent_expandsComponentsAndPartialsAndRegistersOnlyLogicBackedComponents():void { + public static function componentDebugFlags():array { + return [[null], [false], [true]]; + } + + #[DataProvider("componentDebugFlags")] + public function testProcessPartialContent_expandsComponentsAndPartialsAndRegistersOnlyLogicBackedComponents(?bool $enabled):void { LogConfig::addHandler(new TestLogHandler()); file_put_contents( $this->componentDir . "/site-card.html", @@ -77,6 +86,7 @@ public function testProcessPartialContent_expandsComponentsAndPartialsAndRegiste $processor = new HTMLDocumentProcessor( ltrim(substr($this->componentDir, strlen(getcwd())), "/"), ltrim(substr($this->partialDir, strlen(getcwd())), "/"), + new DebugLogger(new Config(new ConfigSection("logger", $enabled === null ? [] : ["debug_html_components" => $enabled ? "true" : "false"]))), ); $componentList = $processor->processPartialContent($document); @@ -94,7 +104,12 @@ public function testProcessPartialContent_expandsComponentsAndPartialsAndRegiste self::assertSame("section", strtolower($document->body->firstElementChild->tagName)); self::assertStringContainsString("
Page
", (string)$document); self::assertStringContainsString("", (string)$document); - self::assertCount(1, TestLogHandler::$records); + if(!$enabled) { + self::assertSame([], TestLogHandler::$records); + return; + } + self::assertCount(2, TestLogHandler::$records); + array_shift(TestLogHandler::$records); self::assertSame("DEBUG", TestLogHandler::$records[0]["level"]); self::assertSame("Component detected without matching logic file", TestLogHandler::$records[0]["message"]); self::assertSame("no-logic", TestLogHandler::$records[0]["context"]["component"]); From ecfecd97c55a5195fd2568e18d4663e8ac1d8202 Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Sat, 21 Nov 2026 17:00:18 +0000 Subject: [PATCH 2/2] feature: debug logging opt-in closes #752 --- test/phpunit/Debug/DebugLoggerTest.php | 64 ++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 test/phpunit/Debug/DebugLoggerTest.php diff --git a/test/phpunit/Debug/DebugLoggerTest.php b/test/phpunit/Debug/DebugLoggerTest.php new file mode 100644 index 00000000..a2710bce --- /dev/null +++ b/test/phpunit/Debug/DebugLoggerTest.php @@ -0,0 +1,64 @@ +loggerState[$name] = $property->getValue(); + $property->setValue(null, $name === "defaultHandlerLevel" ? "DEBUG" : []); + } + TestLogHandler::$records = []; + } + + protected function tearDown():void { + foreach($this->loggerState as $name => $value) { + (new \ReflectionProperty(LogConfig::class, $name))->setValue(null, $value); + } + TestLogHandler::$records = []; + } + + public static function categories():array { + return array_map(fn($category) => [$category], [ + "html_components", "html_partials", "requests", "routing", + "logic", "views", "csrf", "services", + ]); + } + + #[DataProvider("categories")] + public function testCategoriesAreIndependentAndRespectMinimumLevel(string $category):void { + LogConfig::addHandler(new TestLogHandler(), "DEBUG"); + $logger = new DebugLogger(new Config(new ConfigSection("logger", [ + "debug_" . $category => "true", + "debug_disabled" => "false", + ]))); + $logger->log("disabled", "Disabled"); + $logger->log("missing", "Missing"); + (new DebugLogger())->log($category, "No config"); + $logger->log($category, "Enabled", ["file" => "page/index.php"]); + self::assertSame([[ + "level" => "DEBUG", + "message" => "Enabled", + "context" => ["file" => "page/index.php"], + ]], TestLogHandler::$records); + + foreach(["handlers", "handlerMinLevels", "handlerMaxLevels"] as $name) { + (new \ReflectionProperty(LogConfig::class, $name))->setValue(null, []); + } + LogConfig::addHandler(new TestLogHandler(), "INFO"); + $logger->log($category, "Below minimum"); + self::assertCount(1, TestLogHandler::$records); + } +}