-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLog.php
525 lines (494 loc) · 17.4 KB
/
Log.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.2.9
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Log;
use Cake\Core\StaticConfigTrait;
use Cake\Log\Engine\BaseLog;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
/**
* Logs messages to configured Log adapters. One or more adapters
* can be configured using Cake Logs's methods. If you don't
* configure any adapters, and write to Log, the messages will be
* ignored.
*
* ### Configuring Log adapters
*
* You can configure log adapters in your applications `config/app.php` file.
* A sample configuration would look like:
*
* ```
* Log::setConfig('my_log', ['className' => 'FileLog']);
* ```
*
* You can define the className as any fully namespaced classname or use a short hand
* classname to use loggers in the `App\Log\Engine` & `Cake\Log\Engine` namespaces.
* You can also use plugin short hand to use logging classes provided by plugins.
*
* Log adapters are required to implement `Psr\Log\LoggerInterface`, and there is a
* built-in base class (`Cake\Log\Engine\BaseLog`) that can be used for custom loggers.
*
* Outside of the `className` key, all other configuration values will be passed to the
* logging adapter's constructor as an array.
*
* ### Logging levels
*
* When configuring loggers, you can set which levels a logger will handle.
* This allows you to disable debug messages in production for example:
*
* ```
* Log::setConfig('default', [
* 'className' => 'File',
* 'path' => LOGS,
* 'levels' => ['error', 'critical', 'alert', 'emergency']
* ]);
* ```
*
* The above logger would only log error messages or higher. Any
* other log messages would be discarded.
*
* ### Logging scopes
*
* When configuring loggers you can define the active scopes the logger
* is for. If defined, only the listed scopes will be handled by the
* logger. If you don't define any scopes an adapter will catch
* all scopes that match the handled levels.
*
* ```
* Log::setConfig('payments', [
* 'className' => 'File',
* 'scopes' => ['payment', 'order']
* ]);
* ```
*
* The above logger will only capture log entries made in the
* `payment` and `order` scopes. All other scopes including the
* undefined scope will be ignored.
*
* ### Writing to the log
*
* You write to the logs using Log::write(). See its documentation for more information.
*
* ### Logging Levels
*
* By default Cake Log supports all the log levels defined in
* RFC 5424. When logging messages you can either use the named methods,
* or the correct constants with `write()`:
*
* ```
* Log::error('Something horrible happened');
* Log::write(LOG_ERR, 'Something horrible happened');
* ```
*
* ### Logging scopes
*
* When logging messages and configuring log adapters, you can specify
* 'scopes' that the logger will handle. You can think of scopes as subsystems
* in your application that may require different logging setups. For
* example in an e-commerce application you may want to handle logged errors
* in the cart and ordering subsystems differently than the rest of the
* application. By using scopes you can control logging for each part
* of your application and also use standard log levels.
*/
class Log
{
use StaticConfigTrait {
setConfig as protected _setConfig;
}
/**
* An array mapping url schemes to fully qualified Log engine class names
*
* @var string[]
* @psalm-var array<string, class-string>
*/
protected static $_dsnClassMap = [
'console' => Engine\ConsoleLog::class,
'file' => Engine\FileLog::class,
'syslog' => Engine\SyslogLog::class,
];
/**
* Internal flag for tracking whether or not configuration has been changed.
*
* @var bool
*/
protected static $_dirtyConfig = false;
/**
* LogEngineRegistry class
*
* @var \Cake\Log\LogEngineRegistry
*/
protected static $_registry;
/**
* Handled log levels
*
* @var string[]
*/
protected static $_levels = [
'emergency',
'alert',
'critical',
'error',
'warning',
'notice',
'info',
'debug',
];
/**
* Log levels as detailed in RFC 5424
* https://tools.ietf.org/html/rfc5424
*
* @var array
*/
protected static $_levelMap = [
'emergency' => LOG_EMERG,
'alert' => LOG_ALERT,
'critical' => LOG_CRIT,
'error' => LOG_ERR,
'warning' => LOG_WARNING,
'notice' => LOG_NOTICE,
'info' => LOG_INFO,
'debug' => LOG_DEBUG,
];
/**
* Initializes registry and configurations
*
* @return void
*/
protected static function _init(): void
{
if (empty(static::$_registry)) {
static::$_registry = new LogEngineRegistry();
}
if (static::$_dirtyConfig) {
static::_loadConfig();
}
static::$_dirtyConfig = false;
}
/**
* Load the defined configuration and create all the defined logging
* adapters.
*
* @return void
*/
protected static function _loadConfig(): void
{
foreach (static::$_config as $name => $properties) {
if (isset($properties['engine'])) {
$properties['className'] = $properties['engine'];
}
if (!static::$_registry->has((string)$name)) {
static::$_registry->load((string)$name, $properties);
}
}
}
/**
* Reset all the connected loggers. This is useful to do when changing the logging
* configuration or during testing when you want to reset the internal state of the
* Log class.
*
* Resets the configured logging adapters, as well as any custom logging levels.
* This will also clear the configuration data.
*
* @return void
*/
public static function reset(): void
{
if (!empty(static::$_registry)) {
static::$_registry->reset();
}
static::$_config = [];
static::$_dirtyConfig = true;
}
/**
* Gets log levels
*
* Call this method to obtain current
* level configuration.
*
* @return string[] Active log levels
*/
public static function levels(): array
{
return static::$_levels;
}
/**
* This method can be used to define logging adapters for an application
* or read existing configuration.
*
* To change an adapter's configuration at runtime, first drop the adapter and then
* reconfigure it.
*
* Loggers will not be constructed until the first log message is written.
*
* ### Usage
*
* Setting a cache engine up.
*
* ```
* Log::setConfig('default', $settings);
* ```
*
* Injecting a constructed adapter in:
*
* ```
* Log::setConfig('default', $instance);
* ```
*
* Using a factory function to get an adapter:
*
* ```
* Log::setConfig('default', function () { return new FileLog(); });
* ```
*
* Configure multiple adapters at once:
*
* ```
* Log::setConfig($arrayOfConfig);
* ```
*
* @param string|array $key The name of the logger config, or an array of multiple configs.
* @param array|null $config An array of name => config data for adapter.
* @return void
* @throws \BadMethodCallException When trying to modify an existing config.
*/
public static function setConfig($key, $config = null): void
{
static::_setConfig($key, $config);
static::$_dirtyConfig = true;
}
/**
* Get a logging engine.
*
* @param string $name Key name of a configured adapter to get.
* @return \Psr\Log\LoggerInterface|null Instance of LoggerInterface or false if not found
*/
public static function engine(string $name): ?LoggerInterface
{
static::_init();
if (static::$_registry->{$name}) {
return static::$_registry->{$name};
}
return null;
}
/**
* Writes the given message and type to all of the configured log adapters.
* Configured adapters are passed both the $level and $message variables. $level
* is one of the following strings/values.
*
* ### Levels:
*
* - `LOG_EMERG` => 'emergency',
* - `LOG_ALERT` => 'alert',
* - `LOG_CRIT` => 'critical',
* - `LOG_ERR` => 'error',
* - `LOG_WARNING` => 'warning',
* - `LOG_NOTICE` => 'notice',
* - `LOG_INFO` => 'info',
* - `LOG_DEBUG` => 'debug',
*
* ### Basic usage
*
* Write a 'warning' message to the logs:
*
* ```
* Log::write('warning', 'Stuff is broken here');
* ```
*
* ### Using scopes
*
* When writing a log message you can define one or many scopes for the message.
* This allows you to handle messages differently based on application section/feature.
*
* ```
* Log::write('warning', 'Payment failed', ['scope' => 'payment']);
* ```
*
* When configuring loggers you can configure the scopes a particular logger will handle.
* When using scopes, you must ensure that the level of the message, and the scope of the message
* intersect with the defined levels & scopes for a logger.
*
* ### Unhandled log messages
*
* If no configured logger can handle a log message (because of level or scope restrictions)
* then the logged message will be ignored and silently dropped. You can check if this has happened
* by inspecting the return of write(). If false the message was not handled.
*
* @param int|string $level The severity level of the message being written.
* The value must be an integer or string matching a known level.
* @param string $message Message content to log
* @param string|array $context Additional data to be used for logging the message.
* The special `scope` key can be passed to be used for further filtering of the
* log engines to be used. If a string or a numerically index array is passed, it
* will be treated as the `scope` key.
* See Cake\Log\Log::setConfig() for more information on logging scopes.
* @return bool Success
* @throws \InvalidArgumentException If invalid level is passed.
*/
public static function write($level, string $message, $context = []): bool
{
static::_init();
if (is_int($level) && in_array($level, static::$_levelMap, true)) {
$level = array_search($level, static::$_levelMap, true);
}
if (!in_array($level, static::$_levels, true)) {
/** @psalm-suppress PossiblyFalseArgument */
throw new InvalidArgumentException(sprintf('Invalid log level `%s`', $level));
}
$logged = false;
$context = (array)$context;
if (isset($context[0])) {
$context = ['scope' => $context];
}
$context += ['scope' => []];
foreach (static::$_registry->loaded() as $streamName) {
$logger = static::$_registry->{$streamName};
$levels = $scopes = null;
if ($logger instanceof BaseLog) {
$levels = $logger->levels();
$scopes = $logger->scopes();
}
if ($scopes === null) {
$scopes = [];
}
$correctLevel = empty($levels) || in_array($level, $levels, true);
$inScope = $scopes === false && empty($context['scope']) || $scopes === [] ||
is_array($scopes) && array_intersect((array)$context['scope'], $scopes);
if ($correctLevel && $inScope) {
$logger->log($level, $message, $context);
$logged = true;
}
}
return $logged;
}
/**
* Convenience method to log emergency messages
*
* @param string $message log message
* @param string|array $context Additional data to be used for logging the message.
* The special `scope` key can be passed to be used for further filtering of the
* log engines to be used. If a string or a numerically index array is passed, it
* will be treated as the `scope` key.
* See Cake\Log\Log::setConfig() for more information on logging scopes.
* @return bool Success
*/
public static function emergency(string $message, $context = []): bool
{
return static::write(__FUNCTION__, $message, $context);
}
/**
* Convenience method to log alert messages
*
* @param string $message log message
* @param string|array $context Additional data to be used for logging the message.
* The special `scope` key can be passed to be used for further filtering of the
* log engines to be used. If a string or a numerically index array is passed, it
* will be treated as the `scope` key.
* See Cake\Log\Log::setConfig() for more information on logging scopes.
* @return bool Success
*/
public static function alert(string $message, $context = []): bool
{
return static::write(__FUNCTION__, $message, $context);
}
/**
* Convenience method to log critical messages
*
* @param string $message log message
* @param string|array $context Additional data to be used for logging the message.
* The special `scope` key can be passed to be used for further filtering of the
* log engines to be used. If a string or a numerically index array is passed, it
* will be treated as the `scope` key.
* See Cake\Log\Log::setConfig() for more information on logging scopes.
* @return bool Success
*/
public static function critical(string $message, $context = []): bool
{
return static::write(__FUNCTION__, $message, $context);
}
/**
* Convenience method to log error messages
*
* @param string $message log message
* @param string|array $context Additional data to be used for logging the message.
* The special `scope` key can be passed to be used for further filtering of the
* log engines to be used. If a string or a numerically index array is passed, it
* will be treated as the `scope` key.
* See Cake\Log\Log::setConfig() for more information on logging scopes.
* @return bool Success
*/
public static function error(string $message, $context = []): bool
{
return static::write(__FUNCTION__, $message, $context);
}
/**
* Convenience method to log warning messages
*
* @param string $message log message
* @param string|array $context Additional data to be used for logging the message.
* The special `scope` key can be passed to be used for further filtering of the
* log engines to be used. If a string or a numerically index array is passed, it
* will be treated as the `scope` key.
* See Cake\Log\Log::setConfig() for more information on logging scopes.
* @return bool Success
*/
public static function warning(string $message, $context = []): bool
{
return static::write(__FUNCTION__, $message, $context);
}
/**
* Convenience method to log notice messages
*
* @param string $message log message
* @param string|array $context Additional data to be used for logging the message.
* The special `scope` key can be passed to be used for further filtering of the
* log engines to be used. If a string or a numerically index array is passed, it
* will be treated as the `scope` key.
* See Cake\Log\Log::setConfig() for more information on logging scopes.
* @return bool Success
*/
public static function notice(string $message, $context = []): bool
{
return static::write(__FUNCTION__, $message, $context);
}
/**
* Convenience method to log debug messages
*
* @param string $message log message
* @param string|array $context Additional data to be used for logging the message.
* The special `scope` key can be passed to be used for further filtering of the
* log engines to be used. If a string or a numerically index array is passed, it
* will be treated as the `scope` key.
* See Cake\Log\Log::setConfig() for more information on logging scopes.
* @return bool Success
*/
public static function debug(string $message, $context = []): bool
{
return static::write(__FUNCTION__, $message, $context);
}
/**
* Convenience method to log info messages
*
* @param string $message log message
* @param string|array $context Additional data to be used for logging the message.
* The special `scope` key can be passed to be used for further filtering of the
* log engines to be used. If a string or a numerically index array is passed, it
* will be treated as the `scope` key.
* See Cake\Log\Log::setConfig() for more information on logging scopes.
* @return bool Success
*/
public static function info(string $message, $context = []): bool
{
return static::write(__FUNCTION__, $message, $context);
}
}