PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Log/Log.php

https://github.com/binondord/cakephp
PHP | 528 lines | 152 code | 31 blank | 345 comment | 18 complexity | 29544e467531713ffa28c8c774a6e0fb MD5 | raw file
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @since 0.2.9
  12. * @license http://www.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::config('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::config('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::config('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. config as protected _config;
  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 LogEngineRegistry
  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. * http://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. * Reading config data back:
  232. *
  233. * ```
  234. * Log::config('default');
  235. * ```
  236. *
  237. * Setting a cache engine up.
  238. *
  239. * ```
  240. * Log::config('default', $settings);
  241. * ```
  242. *
  243. * Injecting a constructed adapter in:
  244. *
  245. * ```
  246. * Log::config('default', $instance);
  247. * ```
  248. *
  249. * Using a factory function to get an adapter:
  250. *
  251. * ```
  252. * Log::config('default', function () { return new FileLog(); });
  253. * ```
  254. *
  255. * Configure multiple adapters at once:
  256. *
  257. * ```
  258. * Log::config($arrayOfConfig);
  259. * ```
  260. *
  261. * @param string|array $key The name of the logger config, or an array of multiple configs.
  262. * @param array|null $config An array of name => config data for adapter.
  263. * @return mixed null when adding configuration and an array of configuration data when reading.
  264. * @throws \BadMethodCallException When trying to modify an existing config.
  265. */
  266. public static function config($key, $config = null)
  267. {
  268. $return = static::_config($key, $config);
  269. if ($return !== null) {
  270. return $return;
  271. }
  272. static::$_dirtyConfig = true;
  273. }
  274. /**
  275. * Get a logging engine.
  276. *
  277. * @param string $name Key name of a configured adapter to get.
  278. * @return mixed Instance of BaseLog or false if not found
  279. */
  280. public static function engine($name)
  281. {
  282. static::_init();
  283. if (static::$_registry->{$name}) {
  284. return static::$_registry->{$name};
  285. }
  286. return false;
  287. }
  288. /**
  289. * Writes the given message and type to all of the configured log adapters.
  290. * Configured adapters are passed both the $level and $message variables. $level
  291. * is one of the following strings/values.
  292. *
  293. * ### Levels:
  294. *
  295. * - `LOG_EMERG` => 'emergency',
  296. * - `LOG_ALERT` => 'alert',
  297. * - `LOG_CRIT` => 'critical',
  298. * - `LOG_ERR` => 'error',
  299. * - `LOG_WARNING` => 'warning',
  300. * - `LOG_NOTICE` => 'notice',
  301. * - `LOG_INFO` => 'info',
  302. * - `LOG_DEBUG` => 'debug',
  303. *
  304. * ### Basic usage
  305. *
  306. * Write a 'warning' message to the logs:
  307. *
  308. * ```
  309. * Log::write('warning', 'Stuff is broken here');
  310. * ```
  311. *
  312. * ### Using scopes
  313. *
  314. * When writing a log message you can define one or many scopes for the message.
  315. * This allows you to handle messages differently based on application section/feature.
  316. *
  317. * ```
  318. * Log::write('warning', 'Payment failed', ['scope' => 'payment']);
  319. * ```
  320. *
  321. * When configuring loggers you can configure the scopes a particular logger will handle.
  322. * When using scopes, you must ensure that the level of the message, and the scope of the message
  323. * intersect with the defined levels & scopes for a logger.
  324. *
  325. * ### Unhandled log messages
  326. *
  327. * If no configured logger can handle a log message (because of level or scope restrictions)
  328. * then the logged message will be ignored and silently dropped. You can check if this has happened
  329. * by inspecting the return of write(). If false the message was not handled.
  330. *
  331. * @param int|string $level The severity level of the message being written.
  332. * The value must be an integer or string matching a known level.
  333. * @param mixed $message Message content to log
  334. * @param string|array $context Additional data to be used for logging the message.
  335. * The special `scope` key can be passed to be used for further filtering of the
  336. * log engines to be used. If a string or a numerically index array is passed, it
  337. * will be treated as the `scope` key.
  338. * See Cake\Log\Log::config() for more information on logging scopes.
  339. * @return bool Success
  340. * @throws \InvalidArgumentException If invalid level is passed.
  341. */
  342. public static function write($level, $message, $context = [])
  343. {
  344. static::_init();
  345. if (is_int($level) && in_array($level, static::$_levelMap)) {
  346. $level = array_search($level, static::$_levelMap);
  347. }
  348. if (!in_array($level, static::$_levels)) {
  349. throw new InvalidArgumentException(sprintf('Invalid log level "%s"', $level));
  350. }
  351. $logged = false;
  352. $context = (array)$context;
  353. if (isset($context[0])) {
  354. $context = ['scope' => $context];
  355. }
  356. $context += ['scope' => []];
  357. foreach (static::$_registry->loaded() as $streamName) {
  358. $logger = static::$_registry->{$streamName};
  359. $levels = $scopes = null;
  360. if ($logger instanceof BaseLog) {
  361. $levels = $logger->levels();
  362. $scopes = $logger->scopes();
  363. }
  364. if ($scopes === null) {
  365. $scopes = [];
  366. }
  367. $correctLevel = empty($levels) || in_array($level, $levels);
  368. $inScope = $scopes === false && empty($context['scope']) || $scopes === [] ||
  369. is_array($scopes) && array_intersect($context['scope'], $scopes);
  370. if ($correctLevel && $inScope) {
  371. $logger->log($level, $message, $context);
  372. $logged = true;
  373. }
  374. }
  375. return $logged;
  376. }
  377. /**
  378. * Convenience method to log emergency messages
  379. *
  380. * @param string $message log message
  381. * @param string|array $context Additional data to be used for logging the message.
  382. * The special `scope` key can be passed to be used for further filtering of the
  383. * log engines to be used. If a string or a numerically index array is passed, it
  384. * will be treated as the `scope` key.
  385. * See Cake\Log\Log::config() for more information on logging scopes.
  386. * @return bool Success
  387. */
  388. public static function emergency($message, $context = [])
  389. {
  390. return static::write('emergency', $message, $context);
  391. }
  392. /**
  393. * Convenience method to log alert messages
  394. *
  395. * @param string $message log message
  396. * @param string|array $context Additional data to be used for logging the message.
  397. * The special `scope` key can be passed to be used for further filtering of the
  398. * log engines to be used. If a string or a numerically index array is passed, it
  399. * will be treated as the `scope` key.
  400. * See Cake\Log\Log::config() for more information on logging scopes.
  401. * @return bool Success
  402. */
  403. public static function alert($message, $context = [])
  404. {
  405. return static::write('alert', $message, $context);
  406. }
  407. /**
  408. * Convenience method to log critical messages
  409. *
  410. * @param string $message log message
  411. * @param string|array $context Additional data to be used for logging the message.
  412. * The special `scope` key can be passed to be used for further filtering of the
  413. * log engines to be used. If a string or a numerically index array is passed, it
  414. * will be treated as the `scope` key.
  415. * See Cake\Log\Log::config() for more information on logging scopes.
  416. * @return bool Success
  417. */
  418. public static function critical($message, $context = [])
  419. {
  420. return static::write('critical', $message, $context);
  421. }
  422. /**
  423. * Convenience method to log error messages
  424. *
  425. * @param string $message log message
  426. * @param string|array $context Additional data to be used for logging the message.
  427. * The special `scope` key can be passed to be used for further filtering of the
  428. * log engines to be used. If a string or a numerically index array is passed, it
  429. * will be treated as the `scope` key.
  430. * See Cake\Log\Log::config() for more information on logging scopes.
  431. * @return bool Success
  432. */
  433. public static function error($message, $context = [])
  434. {
  435. return static::write('error', $message, $context);
  436. }
  437. /**
  438. * Convenience method to log warning messages
  439. *
  440. * @param string $message log message
  441. * @param string|array $context Additional data to be used for logging the message.
  442. * The special `scope` key can be passed to be used for further filtering of the
  443. * log engines to be used. If a string or a numerically index array is passed, it
  444. * will be treated as the `scope` key.
  445. * See Cake\Log\Log::config() for more information on logging scopes.
  446. * @return bool Success
  447. */
  448. public static function warning($message, $context = [])
  449. {
  450. return static::write('warning', $message, $context);
  451. }
  452. /**
  453. * Convenience method to log notice messages
  454. *
  455. * @param string $message log message
  456. * @param string|array $context Additional data to be used for logging the message.
  457. * The special `scope` key can be passed to be used for further filtering of the
  458. * log engines to be used. If a string or a numerically index array is passed, it
  459. * will be treated as the `scope` key.
  460. * See Cake\Log\Log::config() for more information on logging scopes.
  461. * @return bool Success
  462. */
  463. public static function notice($message, $context = [])
  464. {
  465. return static::write('notice', $message, $context);
  466. }
  467. /**
  468. * Convenience method to log debug messages
  469. *
  470. * @param string $message log message
  471. * @param string|array $context Additional data to be used for logging the message.
  472. * The special `scope` key can be passed to be used for further filtering of the
  473. * log engines to be used. If a string or a numerically index array is passed, it
  474. * will be treated as the `scope` key.
  475. * See Cake\Log\Log::config() for more information on logging scopes.
  476. * @return bool Success
  477. */
  478. public static function debug($message, $context = [])
  479. {
  480. return static::write('debug', $message, $context);
  481. }
  482. /**
  483. * Convenience method to log info messages
  484. *
  485. * @param string $message log message
  486. * @param string|array $context Additional data to be used for logging the message.
  487. * The special `scope` key can be passed to be used for further filtering of the
  488. * log engines to be used. If a string or a numerically index array is passed, it
  489. * will be treated as the `scope` key.
  490. * See Cake\Log\Log::config() for more information on logging scopes.
  491. * @return bool Success
  492. */
  493. public static function info($message, $context = [])
  494. {
  495. return static::write('info', $message, $context);
  496. }
  497. }