From 0608a4f150eb0ff77d5bd1c3ba0f9f7a5afb6cea Mon Sep 17 00:00:00 2001 From: Yoeri Boven Date: Tue, 7 Mar 2023 21:41:17 +0100 Subject: [PATCH] Exceptions produce an empty object in the log (#10) * fixed bug that left context empty if an exception was thrown * added laravel 10 automated testing * wip --- .github/workflows/run-tests.yml | 4 +++- src/DatabaseHandler.php | 9 +++++++++ tests/DatabaseLoggingTest.php | 12 ++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 39ff7ee..83ba1ee 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -14,11 +14,13 @@ jobs: matrix: os: [ubuntu-latest, windows-latest] php: [8.1] - laravel: [9.*] + laravel: [9.*, 10.*] stability: [prefer-lowest, prefer-stable] include: - laravel: 9.* testbench: 7.* + - laravel: 10.* + testbench: 8.* name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} - ${{ matrix.os }} diff --git a/src/DatabaseHandler.php b/src/DatabaseHandler.php index 598f0bb..fb58835 100644 --- a/src/DatabaseHandler.php +++ b/src/DatabaseHandler.php @@ -3,6 +3,7 @@ namespace Yoeriboven\LaravelLogDb; use Monolog\Handler\AbstractProcessingHandler; +use Throwable; use Yoeriboven\LaravelLogDb\Models\LogMessage; class DatabaseHandler extends AbstractProcessingHandler @@ -12,6 +13,14 @@ class DatabaseHandler extends AbstractProcessingHandler */ protected function write($record): void { + $record = is_array($record) ? $record : $record->toArray(); + + $exception = $record['context']['exception'] ?? null; + + if ($exception instanceof Throwable) { + $record['context']['exception'] = (string) $exception; + } + LogMessage::create([ 'level' => $record['level'], 'level_name' => $record['level_name'], diff --git a/tests/DatabaseLoggingTest.php b/tests/DatabaseLoggingTest.php index 22e9971..8b59c40 100644 --- a/tests/DatabaseLoggingTest.php +++ b/tests/DatabaseLoggingTest.php @@ -3,6 +3,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Log; use Yoeriboven\LaravelLogDb\DatabaseLogger; +use Yoeriboven\LaravelLogDb\Models\LogMessage; uses(RefreshDatabase::class); @@ -29,3 +30,14 @@ 'context' => json_encode(['user_id' => 999]), ]); }); + +it('correctly logs exceptions', function () { + config()->set('logging.default', 'db'); + + report(new Exception('This exception should be logged.')); + + $this->assertStringContainsString( + 'This exception should be logged.', + LogMessage::first()->context['exception'] + ); +});