Skip to content

Commit

Permalink
Add PHP serialization support for context
Browse files Browse the repository at this point in the history
  • Loading branch information
nicksagona committed Nov 10, 2024
1 parent cdef8dd commit 08f300f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Writer/AbstractWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,14 @@ public function getContext(array $context = []): string
}

switch ($format) {
// If the data values needs to be preserved, use JSON encoding or PHP serialization
case 'json':
$messageContext = json_encode($context);
break;
case 'php':
$messageContext = serialize($context);
break;
// Else, complex values like arrays and objects will get reduced to a basic string representation, i.e. [Array]
default:
foreach ($context as $key => $value) {
if (is_array($value)) {
Expand Down
9 changes: 9 additions & 0 deletions tests/LoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,15 @@ public function testJsonContext()
unlink(__DIR__ . '/tmp/test.log');
}

public function testPhpContext()
{
$logger = new Logger(new Writer\File(__DIR__ . '/tmp/test.log'));
$logger->info('This is an info.', ['foo' => 'bar', 'format' => 'php']);
$this->assertStringContainsString('{', file_get_contents(__DIR__ . '/tmp/test.log'));

unlink(__DIR__ . '/tmp/test.log');
}

public function testArrayAndObjectContext()
{
$logger = new Logger(new Writer\File(__DIR__ . '/tmp/test.log'));
Expand Down

0 comments on commit 08f300f

Please sign in to comment.