Log.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright 2005-2012, 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 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @since CakePHP(tm) v 0.2.9
  12. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  13. */
  14. namespace Cake\Log;
  15. use Cake\Core\StaticConfigTrait;
  16. use Cake\Error;
  17. use Cake\Log\Engine\BaseLog;
  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/logging.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 `Cake\Log\LogInterface`, 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. *
  78. * ### Writing to the log
  79. *
  80. * You write to the logs using Log::write(). See its documentation for more information.
  81. *
  82. * ### Logging Levels
  83. *
  84. * By default Cake Log supports all the log levels defined in
  85. * RFC 5424. When logging messages you can either use the named methods,
  86. * or the correct constants with `write()`:
  87. *
  88. * {{{
  89. * Log::error('Something horrible happened');
  90. * Log::write(LOG_ERR, 'Something horrible happened');
  91. * }}}
  92. *
  93. * ### Logging scopes
  94. *
  95. * When logging messages and configuring log adapters, you can specify
  96. * 'scopes' that the logger will handle. You can think of scopes as subsystems
  97. * in your application that may require different logging setups. For
  98. * example in an e-commerce application you may want to handle logged errors
  99. * in the cart and ordering subsystems differently than the rest of the
  100. * application. By using scopes you can control logging for each part
  101. * of your application and also use standard log levels.
  102. */
  103. class Log {
  104. use StaticConfigTrait {
  105. config as protected _config;
  106. }
  107. /**
  108. * Internal flag for tracking whether or not configuration has been changed.
  109. *
  110. * @var boolean
  111. */
  112. protected static $_dirtyConfig = false;
  113. /**
  114. * An array of configured loggers.
  115. *
  116. * @var array
  117. */
  118. protected static $_config = [];
  119. /**
  120. * LogEngineRegistry class
  121. *
  122. * @var LogEngineRegistry
  123. */
  124. protected static $_registry;
  125. /**
  126. * Log levels as detailed in RFC 5424
  127. * http://tools.ietf.org/html/rfc5424
  128. *
  129. * @var array
  130. */
  131. protected static $_levels = array(
  132. LOG_EMERG => 'emergency',
  133. LOG_ALERT => 'alert',
  134. LOG_CRIT => 'critical',
  135. LOG_ERR => 'error',
  136. LOG_WARNING => 'warning',
  137. LOG_NOTICE => 'notice',
  138. LOG_INFO => 'info',
  139. LOG_DEBUG => 'debug',
  140. );
  141. /**
  142. * Mapped log levels
  143. *
  144. * @var array
  145. */
  146. protected static $_levelMap = array(
  147. 'emergency' => LOG_EMERG,
  148. 'alert' => LOG_ALERT,
  149. 'critical' => LOG_CRIT,
  150. 'error' => LOG_ERR,
  151. 'warning' => LOG_WARNING,
  152. 'notice' => LOG_NOTICE,
  153. 'info' => LOG_INFO,
  154. 'debug' => LOG_DEBUG,
  155. );
  156. /**
  157. * initialize ObjectCollection
  158. *
  159. * @return void
  160. */
  161. protected static function _init() {
  162. if (empty(static::$_registry)) {
  163. static::$_registry = new LogEngineRegistry();
  164. }
  165. if (static::$_dirtyConfig) {
  166. static::_loadConfig();
  167. }
  168. static::$_dirtyConfig = false;
  169. }
  170. /**
  171. * Load the defined configuration and create all the defined logging
  172. * adapters.
  173. *
  174. * @return void
  175. */
  176. protected static function _loadConfig() {
  177. foreach (static::$_config as $name => $properties) {
  178. if (isset($properties['engine'])) {
  179. $properties['className'] = $properties['engine'];
  180. }
  181. static::$_registry->load($name, $properties);
  182. }
  183. }
  184. /**
  185. * Reset all the connected loggers. This is useful to do when changing the logging
  186. * configuration or during testing when you want to reset the internal state of the
  187. * Log class.
  188. *
  189. * Resets the configured logging adapters, as well as any custom logging levels.
  190. * This will also clear the configuration data.
  191. *
  192. * @return void
  193. */
  194. public static function reset() {
  195. static::$_registry = null;
  196. static::$_config = [];
  197. static::$_dirtyConfig = true;
  198. }
  199. /**
  200. * Gets log levels
  201. *
  202. * Call this method to obtain current
  203. * level configuration.
  204. *
  205. * @return array active log levels
  206. */
  207. public static function levels() {
  208. return static::$_levels;
  209. }
  210. /**
  211. * This method can be used to define logging adapters for an application
  212. * or read existing configuration.
  213. *
  214. * To change an adapter's configuration at runtime, first drop the adapter and then
  215. * reconfigure it.
  216. *
  217. * Loggers will not be constructed until the first log message is written.
  218. *
  219. * ### Usage
  220. *
  221. * Reading config data back:
  222. *
  223. * `Log::config('default');`
  224. *
  225. * Setting a cache engine up.
  226. *
  227. * `Log::config('default', $settings);`
  228. *
  229. * Injecting a constructed adapter in:
  230. *
  231. * `Log::config('default', $instance);`
  232. *
  233. * Using a factory function to get an adapter:
  234. *
  235. * `Log::config('default', function () { return new FileLog(); });`
  236. *
  237. * Configure multiple adapters at once:
  238. *
  239. * `Log::config($arrayOfConfig);`
  240. *
  241. * @param string|array $key The name of the logger config, or an array of multiple configs.
  242. * @param array $config An array of name => config data for adapter.
  243. * @return mixed null when adding configuration and an array of configuration data when reading.
  244. * @throws Cake\Error\Exception When trying to modify an existing config.
  245. * @see App/Config/logging.php
  246. */
  247. public static function config($key, $config = null) {
  248. $return = static::_config($key, $config);
  249. if ($return !== null) {
  250. return $return;
  251. }
  252. static::$_dirtyConfig = true;
  253. }
  254. /**
  255. * Get a logging engine.
  256. *
  257. * @param string $name Key name of a configured adapter to get.
  258. * @return $mixed instance of BaseLog or false if not found
  259. */
  260. public static function engine($name) {
  261. static::_init();
  262. if (static::$_registry->{$name}) {
  263. return static::$_registry->{$name};
  264. }
  265. return false;
  266. }
  267. /**
  268. * Writes the given message and type to all of the configured log adapters.
  269. * Configured adapters are passed both the $level and $message variables. $level
  270. * is one of the following strings/values.
  271. *
  272. * ### Levels:
  273. *
  274. * - `LOG_EMERG` => 'emergency',
  275. * - `LOG_ALERT` => 'alert',
  276. * - `LOG_CRIT` => 'critical',
  277. * - `LOG_ERR` => 'error',
  278. * - `LOG_WARNING` => 'warning',
  279. * - `LOG_NOTICE` => 'notice',
  280. * - `LOG_INFO` => 'info',
  281. * - `LOG_DEBUG` => 'debug',
  282. *
  283. * ### Basic usage
  284. *
  285. * Write a 'warning' message to the logs:
  286. *
  287. * `Log::write('warning', 'Stuff is broken here');`
  288. *
  289. * ### Using scopes
  290. *
  291. * When writing a log message you can define one or many scopes for the message.
  292. * This allows you to handle messages differently based on application section/feature.
  293. *
  294. * `Log::write('warning', 'Payment failed', 'payment');`
  295. *
  296. * When configuring loggers you can configure the scopes a particular logger will handle.
  297. * When using scopes, you must ensure that the level of the message, and the scope of the message
  298. * intersect with the defined levels & scopes for a logger.
  299. *
  300. * ### Unhandled log messages
  301. *
  302. * If no configured logger can handle a log message (because of level or scope restrictions)
  303. * then the logged message will be ignored and silently dropped. You can check if this has happened
  304. * by inspecting the return of write(). If false the message was not handled.
  305. *
  306. * @param integer|string $level The level of the message being written. The value must be
  307. * an integer or string matching a known level.
  308. * @param string $message Message content to log
  309. * @param string|array $scope The scope(s) a log message is being created in.
  310. * See Cake\Log\Log::config() for more information on logging scopes.
  311. * @return boolean Success
  312. */
  313. public static function write($level, $message, $scope = array()) {
  314. static::_init();
  315. if (is_int($level) && isset(static::$_levels[$level])) {
  316. $level = static::$_levels[$level];
  317. }
  318. $logged = false;
  319. foreach (static::$_registry->loaded() as $streamName) {
  320. $logger = static::$_registry->{$streamName};
  321. $levels = $scopes = null;
  322. if ($logger instanceof BaseLog) {
  323. $levels = $logger->levels();
  324. $scopes = $logger->scopes();
  325. }
  326. $correctLevel = (
  327. empty($levels) ||
  328. in_array($level, $levels)
  329. );
  330. $inScope = (
  331. empty($scopes) ||
  332. count(array_intersect((array)$scope, $scopes)) > 0
  333. );
  334. if ($correctLevel && $inScope) {
  335. $logger->write($level, $message);
  336. $logged = true;
  337. }
  338. }
  339. return $logged;
  340. }
  341. /**
  342. * Convenience method to log emergency messages
  343. *
  344. * @param string $message log message
  345. * @param string|array $scope The scope(s) a log message is being created in.
  346. * See Cake\Log\Log::config() for more information on logging scopes.
  347. * @return boolean Success
  348. */
  349. public static function emergency($message, $scope = array()) {
  350. return static::write(static::$_levelMap['emergency'], $message, $scope);
  351. }
  352. /**
  353. * Convenience method to log alert messages
  354. *
  355. * @param string $message log message
  356. * @param string|array $scope The scope(s) a log message is being created in.
  357. * See Cake\Log\Log::config() for more information on logging scopes.
  358. * @return boolean Success
  359. */
  360. public static function alert($message, $scope = array()) {
  361. return static::write(static::$_levelMap['alert'], $message, $scope);
  362. }
  363. /**
  364. * Convenience method to log critical messages
  365. *
  366. * @param string $message log message
  367. * @param string|array $scope The scope(s) a log message is being created in.
  368. * See Cake\Log\Log::config() for more information on logging scopes.
  369. * @return boolean Success
  370. */
  371. public static function critical($message, $scope = array()) {
  372. return static::write(static::$_levelMap['critical'], $message, $scope);
  373. }
  374. /**
  375. * Convenience method to log error messages
  376. *
  377. * @param string $message log message
  378. * @param string|array $scope The scope(s) a log message is being created in.
  379. * See Cake\Log\Log::config() for more information on logging scopes.
  380. * @return boolean Success
  381. */
  382. public static function error($message, $scope = array()) {
  383. return static::write(static::$_levelMap['error'], $message, $scope);
  384. }
  385. /**
  386. * Convenience method to log warning messages
  387. *
  388. * @param string $message log message
  389. * @param string|array $scope The scope(s) a log message is being created in.
  390. * See Cake\Log\Log::config() for more information on logging scopes.
  391. * @return boolean Success
  392. */
  393. public static function warning($message, $scope = array()) {
  394. return static::write(static::$_levelMap['warning'], $message, $scope);
  395. }
  396. /**
  397. * Convenience method to log notice messages
  398. *
  399. * @param string $message log message
  400. * @param string|array $scope The scope(s) a log message is being created in.
  401. * See Cake\Log\Log::config() for more information on logging scopes.
  402. * @return boolean Success
  403. */
  404. public static function notice($message, $scope = array()) {
  405. return static::write(static::$_levelMap['notice'], $message, $scope);
  406. }
  407. /**
  408. * Convenience method to log debug messages
  409. *
  410. * @param string $message log message
  411. * @param string|array $scope The scope(s) a log message is being created in.
  412. * See Cake\Log\Log::config() for more information on logging scopes.
  413. * @return boolean Success
  414. */
  415. public static function debug($message, $scope = array()) {
  416. return static::write(static::$_levelMap['debug'], $message, $scope);
  417. }
  418. /**
  419. * Convenience method to log info messages
  420. *
  421. * @param string $message log message
  422. * @param string|array $scope The scope(s) a log message is being created in.
  423. * See Cake\Log\Log::config() for more information on logging scopes.
  424. * @return boolean Success
  425. */
  426. public static function info($message, $scope = array()) {
  427. return static::write(static::$_levelMap['info'], $message, $scope);
  428. }
  429. }