Log.php 17 KB

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