Skip to content

Commit 7b38377

Browse files
committed
Fix logger behaviour when a context is present
1 parent e36e40f commit 7b38377

File tree

3 files changed

+37
-4
lines changed

3 files changed

+37
-4
lines changed

src/Logger/ConsoleFormatter.php

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,16 @@ public function __invoke(string $level, string $message, array $context): string
5454
}
5555

5656
if (!empty($context)) {
57-
$message .= ' ' . \json_encode($context, JSON_PARTIAL_OUTPUT_ON_ERROR);
58-
$jsonMsg = \json_last_error_msg();
59-
if (!empty($jsonMsg)) {
60-
$message .= "<could not log full context because of: {$jsonMsg}>";
57+
$jsonMessage = \json_encode($context, JSON_PARTIAL_OUTPUT_ON_ERROR);
58+
if (\json_last_error() !== JSON_ERROR_NONE) {
59+
$jsonMsg = \json_last_error_msg();
60+
if (!empty($jsonMsg)) {
61+
$message .= " <could not log full context because of: {$jsonMsg}>";
62+
}
63+
}
64+
if ($jsonMessage !== false) {
65+
// log even partial messages
66+
$message .= ' ' . $jsonMessage;
6167
}
6268
}
6369

src/Renderer/Json.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ public function render(ServerRequestInterface $request, ResponseInterface $respo
4545
$dataStr = json_encode($data, $opts);
4646
if ($dataStr === false) {
4747
// Check for JSON error
48+
// Note that $dataStr may be !== false even if an error occured, if using JSON_PARTIAL_OUTPUT_ON_ERROR
4849
$err = json_last_error();
4950
if ($err !== JSON_ERROR_NONE) {
5051
$response = $response->withStatus(500);

tests/Logger/ConsoleTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,32 @@ public function testLogException()
4444
$this->assertNotEmpty(stream_get_contents($output));
4545
}
4646

47+
public function testLogWithContext()
48+
{
49+
$output = fopen('php://memory', 'w+');
50+
$logger = new Console(LogLevel::DEBUG, $output);
51+
52+
$logger->error("foo", ['bar' => 'baz']);
53+
54+
rewind($output);
55+
$msg = stream_get_contents($output);
56+
$this->assertNotEmpty($msg);
57+
$this->assertFalse(strpos($msg, 'could not log full context'));
58+
}
59+
60+
public function testLogWithContextNotJsonEncodable()
61+
{
62+
$output = fopen('php://memory', 'w+');
63+
$logger = new Console(LogLevel::DEBUG, $output);
64+
65+
$logger->error("foo", ['bar' => \log(0)]);
66+
67+
rewind($output);
68+
$msg = stream_get_contents($output);
69+
$this->assertNotEmpty($msg);
70+
$this->assertTrue(strpos($msg, 'could not log full context') !== false);
71+
}
72+
4773
public function testLogExceptionWithPrevious()
4874
{
4975
$output = fopen('php://memory', 'w+');

0 commit comments

Comments
 (0)