PageRenderTime 63ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Log/Log.php

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