diff --git a/CHANGELOG.md b/CHANGELOG.md index a09281b76..29fa38bd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ The format is based on Keep a Changelog. - **BREAKING:** `zircote/swagger-php` is updated to 7.8. It removed the static `OpenApi\Generator::scan()`, so the OpenAPI command builds the spec with `(new Generator())->generate()`; the generated `spec.json` is unchanged and still declares OpenAPI 3.0.0. The attributes in the `DefaultApi` and `DemoApi` templates work as they are. An application that calls `Generator::scan()` itself must switch to `(new Generator())->generate()` (#687) - `vaibhavpandeyvpz/phemail`, which `MailTrap` uses to read saved emails, is updated to 2.0. Its API is unchanged, and `MailTrap` behaves as before (#687) - The test suite runs on PHPUnit `^11.5` (a development dependency). Its tests use attributes such as `#[DataProvider]` instead of doc-comment markers, which PHPUnit 12 no longer reads (#687) +- **BREAKING:** The `single` and `daily` log adapters write the context of a log call after the message, as one line of JSON, for example `[2026-11-23 14:02:11] Info: Order paid {"order":1042}`; they ignored it, so a failed cron task lost its `exception`, `file` and `line`. A `trace` that is text stays on its own lines, an exception in the context is written as its class, message, file and line, and a context value that cannot be converted never makes the log call fail. A line without a context is unchanged. A tool that parses log lines must allow the JSON at the end, and passwords or tokens passed in the context now reach the log file. The message stays `string|Stringable`, as PSR-3 defines: `logger()->info([...])` throws a `TypeError`, so put structured data in the context, and a custom adapter that uses `LoggerTrait` must pass `formatMessage()` a string (#613) ### Fixed - The storage adapters no longer raise PHP warnings where they return `false`: `LocalFileSystemAdapter::listDirectory()` returns `false` for a folder that does not exist without calling `scandir()`, `DropboxFileSystemAdapter::put()` returns `false` when the response has no `size`, and `DropboxFileSystemAdapter::isFile()` and `GoogleDriveFileSystemAdapter::isFile()` return `false` when the metadata lacks `.tag`, `kind` or `mimeType` (#687) diff --git a/src/Logger/Traits/LoggerTrait.php b/src/Logger/Traits/LoggerTrait.php index cf3489bc4..5bf784b6b 100644 --- a/src/Logger/Traits/LoggerTrait.php +++ b/src/Logger/Traits/LoggerTrait.php @@ -13,6 +13,7 @@ use Quantum\Logger\Exceptions\LoggerException; use Quantum\Storage\FileSystem; use Stringable; +use Throwable; /** * Trait LoggerTrait @@ -40,18 +41,56 @@ public function report(string $level, string|Stringable $message, ?array $contex } /** - * Formats the log message - * @param string|Stringable|array $message + * Formats the log message: the context follows the message as JSON, and a `trace` + * that is text follows on its own lines; a `trace` that is not text stays in the JSON * @param array|null $context */ - protected function formatMessage(string $level, $message, ?array $context = []): string + protected function formatMessage(string $level, string|Stringable $message, ?array $context = []): string { + $context ??= []; + $trace = $context['trace'] ?? null; + $traceIsText = is_string($trace) || $trace instanceof Stringable; + + if ($trace === null || $traceIsText) { + unset($context['trace']); + } + return sprintf( - '[%s] %s: %s%s', + '[%s] %s: %s%s%s', date('Y-m-d H:i:s'), ucfirst($level), - is_array($message) ? json_encode($message, JSON_PRETTY_PRINT) : (string) $message, - isset($context['trace']) ? (PHP_EOL . $context['trace'] . PHP_EOL) : PHP_EOL + (string) $message, + $context !== [] ? ' ' . $this->encodeContext($context) : '', + $traceIsText ? PHP_EOL . $trace . PHP_EOL : PHP_EOL ); } + + /** + * Encodes the context as one line of JSON: an exception becomes its class, message, file and line, + * a Stringable value its text, and a value JSON cannot encode becomes null; when a value throws + * while it is converted, a marker replaces the context, so logging never fails because of it + * @param array $context + */ + private function encodeContext(array $context): string + { + try { + $values = array_map(static fn (mixed $value): mixed => match (true) { + $value instanceof Throwable => [ + 'class' => $value::class, + 'message' => $value->getMessage(), + 'file' => $value->getFile(), + 'line' => $value->getLine(), + ], + $value instanceof Stringable => (string) $value, + default => $value, + }, $context); + + return json_encode( + $values, + JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR + ) ?: ''; + } catch (Throwable) { + return '{"context":"not encodable"}'; + } + } } diff --git a/tests/Unit/Logger/Adapters/DailyAdapterTest.php b/tests/Unit/Logger/Adapters/DailyAdapterTest.php index daac9bf01..91ec9ccd1 100644 --- a/tests/Unit/Logger/Adapters/DailyAdapterTest.php +++ b/tests/Unit/Logger/Adapters/DailyAdapterTest.php @@ -50,4 +50,17 @@ public function testDailyAdapterReportWritesToFile(): void $this->fs->remove($logFile); } + + public function testDailyAdapterWritesTheContextAsJsonAfterTheMessage(): void + { + $this->adapter->report('info', 'Order paid', ['order' => 1042]); + + $logFile = base_dir() . DS . 'logs' . DS . date('Y-m-d') . '.log'; + + $logContent = $this->fs->get($logFile); + + $this->fs->remove($logFile); + + $this->assertStringContainsString('Info: Order paid {"order":1042}' . PHP_EOL, $logContent); + } } diff --git a/tests/Unit/Logger/Adapters/MessageAdapterTest.php b/tests/Unit/Logger/Adapters/MessageAdapterTest.php index 99ebf6461..addf2ef6d 100644 --- a/tests/Unit/Logger/Adapters/MessageAdapterTest.php +++ b/tests/Unit/Logger/Adapters/MessageAdapterTest.php @@ -63,4 +63,11 @@ public function testReportKeepsTheLastThousandMessagesByDefault(): void $this->assertSame(['info' => 'Message 2'], $messages[0]); $this->assertSame(['info' => 'Message 1001'], $messages[999]); } + + public function testReportKeepsOnlyTheLevelAndTheMessageOfAReportWithContext(): void + { + $this->adapter->report('error', 'Failed', ['task' => 'cleanup', 'trace' => '#0 main']); + + $this->assertSame([['error' => 'Failed']], $this->adapter->getMessages()); + } } diff --git a/tests/Unit/Logger/Adapters/SingleAdapterTest.php b/tests/Unit/Logger/Adapters/SingleAdapterTest.php index 98785210f..f8ca000d6 100644 --- a/tests/Unit/Logger/Adapters/SingleAdapterTest.php +++ b/tests/Unit/Logger/Adapters/SingleAdapterTest.php @@ -5,20 +5,41 @@ use Quantum\Logger\Exceptions\LoggerException; use Quantum\Logger\Adapters\SingleAdapter; use Quantum\Tests\Unit\AppTestCase; +use RuntimeException; +use Stringable; class SingleAdapterTest extends AppTestCase { + private const LINE_START = '/^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] '; + private SingleAdapter $adapter; + private string $logFile; + public function setUp(): void { parent::setUp(); + $this->logFile = base_dir() . DS . 'logs' . DS . 'app.log'; + + if ($this->fs->exists($this->logFile)) { + $this->fs->remove($this->logFile); + } + $this->adapter = new SingleAdapter([ - 'path' => base_dir() . DS . 'logs' . DS . 'app.log', + 'path' => $this->logFile, ]); } + public function tearDown(): void + { + if ($this->fs->exists($this->logFile)) { + $this->fs->remove($this->logFile); + } + + parent::tearDown(); + } + public function testSingleAdapterInstance(): void { $this->assertInstanceOf(SingleAdapter::class, $this->adapter); @@ -41,13 +62,149 @@ public function testSingleAdapterReportWritesToFile(): void $this->adapter->report($level, $message, $context); - $logFile = base_dir() . DS . 'logs' . DS . 'app.log'; - - $this->assertTrue($this->fs->exists($logFile)); + $this->assertTrue($this->fs->exists($this->logFile)); - $logContent = $this->fs->get($logFile); + $logContent = $this->fs->get($this->logFile); $this->assertStringContainsString('Test log message', $logContent); + } + + public function testSingleAdapterWritesOnlyTheMessageWithoutContext(): void + { + $this->adapter->report('info', 'Order paid'); + + $this->assertMatchesRegularExpression(self::LINE_START . 'Info: Order paid' . preg_quote(PHP_EOL, '/') . '$/', $this->written()); + } + + public function testSingleAdapterWritesTheContextAsJsonAfterTheMessage(): void + { + $this->adapter->report('info', 'Order paid', ['order' => 1042, 'status' => 'paid']); + + $this->assertMatchesRegularExpression( + self::LINE_START . preg_quote('Info: Order paid {"order":1042,"status":"paid"}' . PHP_EOL, '/') . '$/', + $this->written() + ); + } + + public function testSingleAdapterKeepsTheTraceOnItsOwnLine(): void + { + $this->adapter->report('error', 'Failed', ['trace' => '#0 main']); + + $this->assertMatchesRegularExpression( + self::LINE_START . preg_quote('Error: Failed' . PHP_EOL . '#0 main' . PHP_EOL, '/') . '$/', + $this->written() + ); + } + + public function testSingleAdapterWritesTheContextBeforeTheTrace(): void + { + $this->adapter->report('error', 'Failed', ['task' => 'cleanup', 'trace' => '#0 main']); + + $this->assertMatchesRegularExpression( + self::LINE_START . preg_quote('Error: Failed {"task":"cleanup"}' . PHP_EOL . '#0 main' . PHP_EOL, '/') . '$/', + $this->written() + ); + } + + public function testSingleAdapterWritesAnExceptionInTheContextReadably(): void + { + $exception = new RuntimeException('Disk full'); + + $this->adapter->report('error', 'Failed', ['exception' => $exception]); + + $expected = json_encode([ + 'exception' => [ + 'class' => RuntimeException::class, + 'message' => 'Disk full', + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + ], + ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + + $this->assertStringContainsString('Error: Failed ' . $expected . PHP_EOL, $this->written()); + } + + public function testSingleAdapterWritesAStringableValueAsItsText(): void + { + $value = new class () implements Stringable { + public function __toString(): string + { + return 'order-1042'; + } + }; + + $this->adapter->report('info', 'Order paid', ['order' => $value]); - $this->fs->remove($logFile); + $this->assertStringContainsString('Info: Order paid {"order":"order-1042"}' . PHP_EOL, $this->written()); + } + + public function testSingleAdapterWritesPathsAndUnicodeReadably(): void + { + $this->adapter->report('info', 'Saved', ['file' => '/var/log/café.txt']); + + $this->assertStringContainsString('Info: Saved {"file":"/var/log/café.txt"}' . PHP_EOL, $this->written()); + } + + public function testSingleAdapterWritesTheLineWhenTheContextHasInvalidUtf8(): void + { + $this->adapter->report('info', 'Received', ['name' => "caf\xE9"]); + + $this->assertStringContainsString("Info: Received {\"name\":\"caf\u{FFFD}\"}" . PHP_EOL, $this->written()); + } + + public function testSingleAdapterWritesNullForAValueJsonCannotEncode(): void + { + $resource = fopen('php://memory', 'r'); + + $this->adapter->report('info', 'Opened', ['handle' => $resource, 'mode' => 'r']); + + fclose($resource); + + $this->assertStringContainsString('Info: Opened {"handle":null,"mode":"r"}' . PHP_EOL, $this->written()); + } + + public function testSingleAdapterWritesTheLineWhenAContextValueCannotBeConverted(): void + { + $value = new class () implements Stringable { + public function __toString(): string + { + throw new RuntimeException('Not loaded'); + } + }; + + $this->adapter->report('error', 'Failed', ['user' => $value]); + + $this->assertStringContainsString('Error: Failed {"context":"not encodable"}' . PHP_EOL, $this->written()); + } + + public function testSingleAdapterWritesATraceThatIsNotTextInTheContext(): void + { + $this->adapter->report('error', 'Failed', ['trace' => ['#0 main', '#1 run']]); + + $this->assertMatchesRegularExpression( + self::LINE_START . preg_quote('Error: Failed {"trace":["#0 main","#1 run"]}' . PHP_EOL, '/') . '$/', + $this->written() + ); + } + + public function testSingleAdapterWritesAStringableTraceOnItsOwnLine(): void + { + $trace = new class () implements Stringable { + public function __toString(): string + { + return '#0 main'; + } + }; + + $this->adapter->report('error', 'Failed', ['trace' => $trace]); + + $this->assertMatchesRegularExpression( + self::LINE_START . preg_quote('Error: Failed' . PHP_EOL . '#0 main' . PHP_EOL, '/') . '$/', + $this->written() + ); + } + + private function written(): string + { + return $this->fs->get($this->logFile); } } diff --git a/tests/Unit/Logger/LoggerTest.php b/tests/Unit/Logger/LoggerTest.php index f65d19db4..59f234b79 100644 --- a/tests/Unit/Logger/LoggerTest.php +++ b/tests/Unit/Logger/LoggerTest.php @@ -9,6 +9,7 @@ use Quantum\Logger\Logger; use Psr\Log\LogLevel; use Stringable; +use TypeError; class LoggerTest extends AppTestCase { @@ -66,6 +67,13 @@ public function __toString(): string $this->assertSame([['critical' => $message]], $this->adapter->getMessages()); } + public function testLoggerRejectsAnArrayMessage(): void + { + $this->expectException(TypeError::class); + + $this->logger->info(['order' => 1042]); + } + /** * @return array */