Skip to content

Commit

Permalink
Exceptions produce an empty object in the log (#10)
Browse files Browse the repository at this point in the history
* fixed bug that left context empty if an exception was thrown

* added laravel 10 automated testing

* wip
  • Loading branch information
yoeriboven authored Mar 7, 2023
1 parent bfb6399 commit 0608a4f
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
4 changes: 3 additions & 1 deletion .github/workflows/run-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}

Expand Down
9 changes: 9 additions & 0 deletions src/DatabaseHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Yoeriboven\LaravelLogDb;

use Monolog\Handler\AbstractProcessingHandler;
use Throwable;
use Yoeriboven\LaravelLogDb\Models\LogMessage;

class DatabaseHandler extends AbstractProcessingHandler
Expand All @@ -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'],
Expand Down
12 changes: 12 additions & 0 deletions tests/DatabaseLoggingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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']
);
});

0 comments on commit 0608a4f

Please sign in to comment.