Skip to content

Commit 4cde567

Browse files
committed
refactor Logger
1 parent 0e99ab6 commit 4cde567

2 files changed

Lines changed: 32 additions & 77 deletions

File tree

system/Log/Logger.php

Lines changed: 31 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,11 @@ class Logger implements LoggerInterface
5454
];
5555

5656
/**
57-
* Array of levels to be logged.
58-
* The rest will be ignored.
59-
* Set in Config/logger.php
57+
* Array of levels to be logged. The rest will be ignored.
6058
*
61-
* @var array
59+
* Set in app/Config/Logger.php
60+
*
61+
* @var list<string>
6262
*/
6363
protected $loggableLevels = [];
6464

@@ -86,7 +86,7 @@ class Logger implements LoggerInterface
8686
/**
8787
* Caches instances of the handlers.
8888
*
89-
* @var array
89+
* @var array<class-string<HandlerInterface>, HandlerInterface>
9090
*/
9191
protected $handlers = [];
9292

@@ -96,14 +96,14 @@ class Logger implements LoggerInterface
9696
* value is an associative array of configuration
9797
* items.
9898
*
99-
* @var array<class-string, array<string, int|list<string>|string>>
99+
* @var array<class-string<HandlerInterface>, array<string, int|list<string>|string>>
100100
*/
101101
protected $handlerConfig = [];
102102

103103
/**
104104
* Caches logging calls for debugbar.
105105
*
106-
* @var array
106+
* @var list<array{level: string, msg: string}>
107107
*/
108108
public $logCache;
109109

@@ -123,41 +123,41 @@ class Logger implements LoggerInterface
123123
*/
124124
public function __construct($config, bool $debug = CI_DEBUG)
125125
{
126-
$this->loggableLevels = is_array($config->threshold) ? $config->threshold : range(1, (int) $config->threshold);
126+
$loggableLevels = is_array($config->threshold) ? $config->threshold : range(1, $config->threshold);
127127

128128
// Now convert loggable levels to strings.
129129
// We only use numbers to make the threshold setting convenient for users.
130-
if ($this->loggableLevels !== []) {
131-
$temp = [];
130+
foreach ($loggableLevels as $level) {
131+
/** @var false|string $stringLevel */
132+
$stringLevel = array_search($level, $this->logLevels, true);
132133

133-
foreach ($this->loggableLevels as $level) {
134-
$temp[] = array_search((int) $level, $this->logLevels, true);
134+
if ($stringLevel === false) {
135+
continue;
135136
}
136137

137-
$this->loggableLevels = $temp;
138-
unset($temp);
138+
$this->loggableLevels[] = $stringLevel;
139139
}
140140

141-
$this->dateFormat = $config->dateFormat ?? $this->dateFormat;
141+
if (isset($config->dateFormat)) {
142+
$this->dateFormat = $config->dateFormat;
143+
}
142144

143-
if (! is_array($config->handlers) || $config->handlers === []) {
145+
if ((array) $config->handlers === []) {
144146
throw LogException::forNoHandlers('LoggerConfig');
145147
}
146148

147149
// Save the handler configuration for later.
148150
// Instances will be created on demand.
149151
$this->handlerConfig = $config->handlers;
152+
$this->cacheLogs = $debug;
150153

151-
$this->cacheLogs = $debug;
152154
if ($this->cacheLogs) {
153155
$this->logCache = [];
154156
}
155157
}
156158

157159
/**
158160
* System is unusable.
159-
*
160-
* @param string $message
161161
*/
162162
public function emergency(string|Stringable $message, array $context = []): void
163163
{
@@ -169,8 +169,6 @@ public function emergency(string|Stringable $message, array $context = []): void
169169
*
170170
* Example: Entire website down, database unavailable, etc. This should
171171
* trigger the SMS alerts and wake you up.
172-
*
173-
* @param string $message
174172
*/
175173
public function alert(string|Stringable $message, array $context = []): void
176174
{
@@ -181,8 +179,6 @@ public function alert(string|Stringable $message, array $context = []): void
181179
* Critical conditions.
182180
*
183181
* Example: Application component unavailable, unexpected exception.
184-
*
185-
* @param string $message
186182
*/
187183
public function critical(string|Stringable $message, array $context = []): void
188184
{
@@ -192,8 +188,6 @@ public function critical(string|Stringable $message, array $context = []): void
192188
/**
193189
* Runtime errors that do not require immediate action but should typically
194190
* be logged and monitored.
195-
*
196-
* @param string $message
197191
*/
198192
public function error(string|Stringable $message, array $context = []): void
199193
{
@@ -205,8 +199,6 @@ public function error(string|Stringable $message, array $context = []): void
205199
*
206200
* Example: Use of deprecated APIs, poor use of an API, undesirable things
207201
* that are not necessarily wrong.
208-
*
209-
* @param string $message
210202
*/
211203
public function warning(string|Stringable $message, array $context = []): void
212204
{
@@ -215,8 +207,6 @@ public function warning(string|Stringable $message, array $context = []): void
215207

216208
/**
217209
* Normal but significant events.
218-
*
219-
* @param string $message
220210
*/
221211
public function notice(string|Stringable $message, array $context = []): void
222212
{
@@ -227,8 +217,6 @@ public function notice(string|Stringable $message, array $context = []): void
227217
* Interesting events.
228218
*
229219
* Example: User logs in, SQL logs.
230-
*
231-
* @param string $message
232220
*/
233221
public function info(string|Stringable $message, array $context = []): void
234222
{
@@ -237,8 +225,6 @@ public function info(string|Stringable $message, array $context = []): void
237225

238226
/**
239227
* Detailed debug information.
240-
*
241-
* @param string $message
242228
*/
243229
public function debug(string|Stringable $message, array $context = []): void
244230
{
@@ -248,51 +234,40 @@ public function debug(string|Stringable $message, array $context = []): void
248234
/**
249235
* Logs with an arbitrary level.
250236
*
251-
* @param string $level
252-
* @param string $message
237+
* @param mixed $level
253238
*/
254239
public function log($level, string|Stringable $message, array $context = []): void
255240
{
256241
if (is_numeric($level)) {
257242
$level = array_search((int) $level, $this->logLevels, true);
258243
}
259244

260-
// Is the level a valid level?
261245
if (! array_key_exists($level, $this->logLevels)) {
262246
throw LogException::forInvalidLogLevel($level);
263247
}
264248

265-
// Does the app want to log this right now?
266249
if (! in_array($level, $this->loggableLevels, true)) {
267250
return;
268251
}
269252

270-
// Parse our placeholders
271253
$message = $this->interpolate($message, $context);
272254

273255
if ($this->cacheLogs) {
274-
$this->logCache[] = [
275-
'level' => $level,
276-
'msg' => $message,
277-
];
256+
$this->logCache[] = ['level' => $level, 'msg' => $message];
278257
}
279258

280259
foreach ($this->handlerConfig as $className => $config) {
281260
if (! array_key_exists($className, $this->handlers)) {
282261
$this->handlers[$className] = new $className($config);
283262
}
284263

285-
/**
286-
* @var HandlerInterface $handler
287-
*/
288264
$handler = $this->handlers[$className];
289265

290266
if (! $handler->canHandle($level)) {
291267
continue;
292268
}
293269

294-
// If the handler returns false, then we
295-
// don't execute any other handlers.
270+
// If the handler returns false, then we don't execute any other handlers.
296271
if (! $handler->setDateFormat($this->dateFormat)->handle($level, $message)) {
297272
break;
298273
}
@@ -311,7 +286,8 @@ public function log($level, string|Stringable $message, array $context = []): vo
311286
* {file}
312287
* {line}
313288
*
314-
* @param string $message
289+
* @param string|Stringable $message
290+
* @param array<string, mixed> $context
315291
*
316292
* @return string
317293
*/
@@ -321,7 +297,6 @@ protected function interpolate($message, array $context = [])
321297
return print_r($message, true);
322298
}
323299

324-
// build a replacement array with braces around the context keys
325300
$replace = [];
326301

327302
foreach ($context as $key => $val) {
@@ -335,7 +310,6 @@ protected function interpolate($message, array $context = [])
335310
$replace['{' . $key . '}'] = $val;
336311
}
337312

338-
// Add special placeholders
339313
$replace['{post_vars}'] = '$_POST: ' . print_r($_POST, true);
340314
$replace['{get_vars}'] = '$_GET: ' . print_r($_GET, true);
341315
$replace['{env}'] = ENVIRONMENT;
@@ -362,14 +336,15 @@ protected function interpolate($message, array $context = [])
362336
$replace['{session_vars}'] = '$_SESSION: ' . print_r($_SESSION, true);
363337
}
364338

365-
// interpolate replacement values into the message and return
366339
return strtr($message, $replace);
367340
}
368341

369342
/**
370343
* Determines the file and line that the logging call
371344
* was made from by analyzing the backtrace.
372345
* Find the earliest stack frame that is part of our logging system.
346+
*
347+
* @return array{string, int|string}
373348
*/
374349
public function determineFile(): array
375350
{
@@ -386,28 +361,19 @@ public function determineFile(): array
386361
'notice',
387362
];
388363

389-
// Generate Backtrace info
390-
$trace = \debug_backtrace(0);
364+
$trace = debug_backtrace(0);
391365

392-
// So we search from the bottom (earliest) of the stack frames
393-
$stackFrames = \array_reverse($trace);
366+
$stackFrames = array_reverse($trace);
394367

395-
// Find the first reference to a Logger class method
396368
foreach ($stackFrames as $frame) {
397-
if (\in_array($frame['function'], $logFunctions, true)) {
369+
if (in_array($frame['function'], $logFunctions, true)) {
398370
$file = isset($frame['file']) ? clean_path($frame['file']) : 'unknown';
399371
$line = $frame['line'] ?? 'unknown';
400372

401-
return [
402-
$file,
403-
$line,
404-
];
373+
return [$file, $line];
405374
}
406375
}
407376

408-
return [
409-
'unknown',
410-
'unknown',
411-
];
377+
return ['unknown', 'unknown'];
412378
}
413379
}

tests/system/Log/LoggerTest.php

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
use ReflectionMethod;
2424
use ReflectionNamedType;
2525
use Tests\Support\Log\Handlers\TestHandler;
26-
use TypeError;
2726

2827
/**
2928
* @internal
@@ -42,7 +41,7 @@ protected function tearDown(): void
4241
public function testThrowsExceptionWithBadHandlerSettings(): void
4342
{
4443
$config = new LoggerConfig();
45-
$config->handlers = null;
44+
$config->handlers = [];
4645

4746
$this->expectException(FrameworkException::class);
4847
$this->expectExceptionMessage(lang('Core.noHandlers', ['LoggerConfig']));
@@ -427,16 +426,6 @@ public function testLogLevels(): void
427426
$this->assertSame($expected, $logs[0]);
428427
}
429428

430-
public function testNonStringMessage(): void
431-
{
432-
$this->expectException(TypeError::class);
433-
434-
$config = new LoggerConfig();
435-
$logger = new Logger($config);
436-
437-
$logger->log(5, $config);
438-
}
439-
440429
public function testDetermineFileNoStackTrace(): void
441430
{
442431
$config = new LoggerConfig();

0 commit comments

Comments
 (0)