Skip to content

Commit 80803b5

Browse files
refactor(log): return int from HandlerInterface::handle()
Returning false stopped the handler chain, and built-in handlers returned false on write failure. A failing FileHandler (e.g. bad permissions) silently blocked later handlers such as ErrorlogHandler. handle() now returns RESULT_CONTINUE or RESULT_STOP. Built-in handlers always return RESULT_CONTINUE, so a write failure no longer stops the chain. Logger only stops on RESULT_STOP. BREAKING CHANGE: custom log handlers must change the handle() return type from bool to int and return HandlerInterface::RESULT_CONTINUE (was true) or RESULT_STOP (was false). A handler still declaring `: bool` is a fatal error at class load. See upgrade_480.rst.
1 parent 602733d commit 80803b5

13 files changed

Lines changed: 161 additions & 32 deletions

File tree

‎system/Log/Handlers/ChromeLoggerHandler.php‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,15 +96,13 @@ public function __construct(array $config = [])
9696

9797
/**
9898
* Handles logging the message.
99-
* If the handler returns false, then execution of handlers
100-
* will stop. Any handlers that have not run, yet, will not
101-
* be run.
99+
* Always lets the remaining handlers run.
102100
*
103101
* @param string $level
104102
* @param object|string $message
105103
* @param array<string, mixed> $context
106104
*/
107-
public function handle($level, $message, array $context = []): bool
105+
public function handle($level, $message, array $context = []): int
108106
{
109107
$message = $this->format($message);
110108

@@ -129,7 +127,7 @@ public function handle($level, $message, array $context = []): bool
129127

130128
$this->sendLogs();
131129

132-
return true;
130+
return self::RESULT_CONTINUE;
133131
}
134132

135133
/**

‎system/Log/Handlers/ErrorlogHandler.php‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,23 +62,23 @@ public function __construct(array $config = [])
6262

6363
/**
6464
* Handles logging the message.
65-
* If the handler returns false, then execution of handlers
66-
* will stop. Any handlers that have not run, yet, will not
67-
* be run.
65+
* Always lets the remaining handlers run, even if `error_log()` fails.
6866
*
6967
* @param string $level
7068
* @param string $message
7169
* @param array<string, mixed> $context
7270
*/
73-
public function handle($level, $message, array $context = []): bool
71+
public function handle($level, $message, array $context = []): int
7472
{
7573
if ($context !== []) {
7674
$message .= ' ' . $this->encodeContext($context);
7775
}
7876

7977
$message = strtoupper($level) . ' --> ' . $message . "\n";
8078

81-
return $this->errorLog($message, $this->messageType);
79+
$this->errorLog($message, $this->messageType);
80+
81+
return self::RESULT_CONTINUE;
8282
}
8383

8484
/**

‎system/Log/Handlers/FileHandler.php‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,17 +65,16 @@ public function __construct(array $config = [])
6565

6666
/**
6767
* Handles logging the message.
68-
* If the handler returns false, then execution of handlers
69-
* will stop. Any handlers that have not run, yet, will not
70-
* be run.
68+
* Always lets the remaining handlers run, even if writing
69+
* the log file fails.
7170
*
7271
* @param string $level
7372
* @param string $message
7473
* @param array<string, mixed> $context
7574
*
7675
* @throws Exception
7776
*/
78-
public function handle($level, $message, array $context = []): bool
77+
public function handle($level, $message, array $context = []): int
7978
{
8079
$filepath = $this->path . 'log-' . date('Y-m-d') . '.' . $this->fileExtension;
8180

@@ -92,7 +91,7 @@ public function handle($level, $message, array $context = []): bool
9291
}
9392

9493
if (! $fp = @fopen($filepath, 'ab')) {
95-
return false;
94+
return self::RESULT_CONTINUE;
9695
}
9796

9897
// Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
@@ -130,6 +129,6 @@ public function handle($level, $message, array $context = []): bool
130129
@chmod($filepath, $this->filePermissions);
131130
}
132131

133-
return is_int($result);
132+
return self::RESULT_CONTINUE;
134133
}
135134
}

‎system/Log/Handlers/HandlerInterface.php‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,32 @@ interface HandlerInterface
2525
*/
2626
public const GLOBAL_CONTEXT_KEY = '_ci_context';
2727

28+
/**
29+
* Returned by `handle()` to let the remaining handlers run.
30+
*/
31+
public const RESULT_CONTINUE = 1;
32+
33+
/**
34+
* Returned by `handle()` to stop the chain. Any handlers that
35+
* have not run, yet, will not be run.
36+
*/
37+
public const RESULT_STOP = 2;
38+
2839
/**
2940
* Handles logging the message.
30-
* If the handler returns false, then execution of handlers
31-
* will stop. Any handlers that have not run, yet, will not
32-
* be run.
41+
* Must return either RESULT_CONTINUE or RESULT_STOP. When RESULT_STOP
42+
* is returned, execution of handlers will stop and any handlers that
43+
* have not run, yet, will not be run. Any other value lets the
44+
* remaining handlers run.
3345
*
3446
* @param string $level
3547
* @param string $message
3648
* @param array<string, mixed> $context Full context array; may contain
3749
* GLOBAL_CONTEXT_KEY with CI global data
50+
*
51+
* @return int One of the RESULT_* constants
3852
*/
39-
public function handle($level, $message, array $context = []): bool;
53+
public function handle($level, $message, array $context = []): int;
4054

4155
/**
4256
* Checks whether the Handler will handle logging items of this

‎system/Log/Logger.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -324,8 +324,8 @@ public function log($level, string|Stringable $message, array $context = []): vo
324324
continue;
325325
}
326326

327-
// If the handler returns false, then we don't execute any other handlers.
328-
if (! $handler->setDateFormat($this->dateFormat)->handle($level, $message, $context)) {
327+
// If the handler asks to stop, then we don't execute any other handlers.
328+
if ($handler->setDateFormat($this->dateFormat)->handle($level, $message, $context) === HandlerInterface::RESULT_STOP) {
329329
break;
330330
}
331331
}

‎tests/_support/Log/Handlers/TestHandler.php‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,22 +58,20 @@ public function __construct(array $config)
5858

5959
/**
6060
* Handles logging the message.
61-
* If the handler returns false, then execution of handlers
62-
* will stop. Any handlers that have not run, yet, will not
63-
* be run.
61+
* Always lets the remaining handlers run.
6462
*
6563
* @param string $level
6664
* @param string $message
6765
* @param array<string, mixed> $context
6866
*/
69-
public function handle($level, $message, array $context = []): bool
67+
public function handle($level, $message, array $context = []): int
7068
{
7169
$date = Time::now()->format($this->dateFormat);
7270

7371
self::$logs[] = strtoupper($level) . ' - ' . $date . ' --> ' . $message;
7472
self::$contexts[] = $context;
7573

76-
return true;
74+
return self::RESULT_CONTINUE;
7775
}
7876

7977
public static function getLogs()

‎tests/system/Log/Handlers/ChromeLoggerHandlerTest.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public function testHandle(): void
4343
$config->handlers['CodeIgniter\Log\Handlers\TestHandler']['handles'] = ['critical'];
4444

4545
$logger = new ChromeLoggerHandler($config->handlers['CodeIgniter\Log\Handlers\TestHandler']);
46-
$this->assertTrue($logger->handle('warning', 'This a log test'));
46+
$this->assertSame(HandlerInterface::RESULT_CONTINUE, $logger->handle('warning', 'This a log test'));
4747
}
4848

4949
public function testSendLogs(): void

‎tests/system/Log/Handlers/ErrorlogHandlerTest.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public function testErrorLoggingWithErrorLog(): void
3535
$logger = $this->getMockedHandler(['handles' => ['critical', 'error']]);
3636
$logger->method('errorLog')->willReturn(true);
3737
$logger->expects($this->once())->method('errorLog')->with("ERROR --> Test message.\n", 0);
38-
$this->assertTrue($logger->handle('error', 'Test message.'));
38+
$this->assertSame(HandlerInterface::RESULT_CONTINUE, $logger->handle('error', 'Test message.'));
3939
}
4040

4141
public function testErrorLoggingAppendsContextAsJson(): void
@@ -44,7 +44,7 @@ public function testErrorLoggingAppendsContextAsJson(): void
4444
$logger->method('errorLog')->willReturn(true);
4545
$logger->expects($this->once())->method('errorLog')
4646
->with("ERROR --> Test message. {\"_ci_context\":{\"foo\":\"bar\"}}\n", 0);
47-
$this->assertTrue($logger->handle('error', 'Test message.', [HandlerInterface::GLOBAL_CONTEXT_KEY => ['foo' => 'bar']]));
47+
$this->assertSame(HandlerInterface::RESULT_CONTINUE, $logger->handle('error', 'Test message.', [HandlerInterface::GLOBAL_CONTEXT_KEY => ['foo' => 'bar']]));
4848
}
4949

5050
/**

‎tests/system/Log/Handlers/FileHandlerTest.php‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public function testHandle(): void
4343

4444
$logger = new MockFileLogger($config->handlers[TestHandler::class]);
4545
$logger->setDateFormat('Y-m-d H:i:s:u');
46-
$this->assertTrue($logger->handle('warning', 'This is a test log'));
46+
$this->assertSame(HandlerInterface::RESULT_CONTINUE, $logger->handle('warning', 'This is a test log'));
4747
}
4848

4949
public function testBasicHandle(): void
@@ -56,7 +56,19 @@ public function testBasicHandle(): void
5656
$logger->setDateFormat('Y-m-d H:i:s:u');
5757
$expected = 'log-' . date('Y-m-d') . '.log';
5858
vfsStream::newFile($expected)->at(vfsStream::setup('root/charlie'))->withContent('This is a test log');
59-
$this->assertTrue($logger->handle('warning', 'This is a test log'));
59+
$this->assertSame(HandlerInterface::RESULT_CONTINUE, $logger->handle('warning', 'This is a test log'));
60+
}
61+
62+
public function testHandleContinuesWhenFileCannotBeOpened(): void
63+
{
64+
$config = new LoggerConfig();
65+
$config->handlers[TestHandler::class]['path'] = $this->start . 'does-not-exist/';
66+
$config->handlers[TestHandler::class]['handles'] = ['critical'];
67+
68+
$logger = new MockFileLogger($config->handlers[TestHandler::class]);
69+
$logger->setDateFormat('Y-m-d H:i:s:u');
70+
71+
$this->assertSame(HandlerInterface::RESULT_CONTINUE, $logger->handle('warning', 'This is a test log'));
6072
}
6173

6274
public function testHandleCreateFile(): void

‎tests/system/Log/LoggerTest.php‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
use CodeIgniter\Exceptions\RuntimeException;
1919
use CodeIgniter\I18n\Time;
2020
use CodeIgniter\Log\Exceptions\LogException;
21+
use CodeIgniter\Log\Handlers\BaseHandler;
22+
use CodeIgniter\Log\Handlers\HandlerInterface;
2123
use CodeIgniter\Test\CIUnitTestCase;
2224
use CodeIgniter\Test\Mock\MockLogger as LoggerConfig;
2325
use PHPUnit\Framework\Attributes\Group;
@@ -95,6 +97,67 @@ public function testLogActuallyLogs(): void
9597
$this->assertSame($expected, $logs[0]);
9698
}
9799

100+
public function testLogRunsRemainingHandlersWhenAHandlerReturnsContinue(): void
101+
{
102+
$config = new LoggerConfig();
103+
$config->handlers = [
104+
$this->getResultHandlerClass() => ['handles' => ['debug'], 'result' => HandlerInterface::RESULT_CONTINUE],
105+
TestHandler::class => ['handles' => ['debug']],
106+
];
107+
108+
$logger = new Logger($config);
109+
$logger->log('debug', 'Test message');
110+
111+
$this->assertCount(1, TestHandler::getLogs());
112+
}
113+
114+
public function testLogStopsRunningHandlersWhenAHandlerReturnsStop(): void
115+
{
116+
$config = new LoggerConfig();
117+
$config->handlers = [
118+
$this->getResultHandlerClass() => ['handles' => ['debug'], 'result' => HandlerInterface::RESULT_STOP],
119+
TestHandler::class => ['handles' => ['debug']],
120+
];
121+
122+
// Handlers are created lazily and TestHandler resets its logs when
123+
// created, so reset them here as it will never be reached.
124+
new TestHandler([]);
125+
126+
$logger = new Logger($config);
127+
$logger->log('debug', 'Test message');
128+
129+
$this->assertCount(0, TestHandler::getLogs());
130+
}
131+
132+
/**
133+
* Returns the class of a handler that returns the `result` value from its config.
134+
*
135+
* @return class-string<HandlerInterface>
136+
*/
137+
private function getResultHandlerClass(): string
138+
{
139+
$handler = new class ([]) extends BaseHandler {
140+
private int $result;
141+
142+
/**
143+
* @param array{handles?: list<string>, result?: int} $config
144+
*/
145+
public function __construct(array $config)
146+
{
147+
parent::__construct($config);
148+
149+
$this->result = $config['result'] ?? HandlerInterface::RESULT_CONTINUE;
150+
}
151+
152+
public function handle($level, $message, array $context = []): int
153+
{
154+
return $this->result;
155+
}
156+
};
157+
158+
return $handler::class;
159+
}
160+
98161
public function testLogDoesnotLogUnhandledLevels(): void
99162
{
100163
$config = new LoggerConfig();

0 commit comments

Comments
 (0)