CakeLog.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. <?php
  2. /**
  3. * Logging.
  4. *
  5. * Log messages to text files.
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * For full copyright and license information, please see the LICENSE.txt
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @package Cake.Log
  19. * @since CakePHP(tm) v 0.2.9
  20. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  21. */
  22. App::uses('LogEngineCollection', 'Log');
  23. /**
  24. * Logs messages to configured Log adapters. One or more adapters
  25. * can be configured using CakeLogs's methods. If you don't
  26. * configure any adapters, and write to the logs a default
  27. * FileLog will be autoconfigured for you.
  28. *
  29. * ### Configuring Log adapters
  30. *
  31. * You can configure log adapters in your applications `bootstrap.php` file.
  32. * A sample configuration would look like:
  33. *
  34. * {{{
  35. * CakeLog::config('my_log', array('engine' => 'File'));
  36. * }}}
  37. *
  38. * See the documentation on CakeLog::config() for more detail.
  39. *
  40. * ### Writing to the log
  41. *
  42. * You write to the logs using CakeLog::write(). See its documentation for more
  43. * information.
  44. *
  45. * ### Logging Levels
  46. *
  47. * By default CakeLog supports all the log levels defined in
  48. * RFC 5424. When logging messages you can either use the named methods,
  49. * or the correct constants with `write()`:
  50. *
  51. * {{{
  52. * CakeLog::error('Something horrible happened');
  53. * CakeLog::write(LOG_ERR, 'Something horrible happened');
  54. * }}}
  55. *
  56. * If you require custom logging levels, you can use CakeLog::levels() to
  57. * append additional logging levels.
  58. *
  59. * ### Logging scopes
  60. *
  61. * When logging messages and configuring log adapters, you can specify
  62. * 'scopes' that the logger will handle. You can think of scopes as subsystems
  63. * in your application that may require different logging setups. For
  64. * example in an e-commerce application you may want to handle logged errors
  65. * in the cart and ordering subsystems differently than the rest of the
  66. * application. By using scopes you can control logging for each part
  67. * of your application and still keep standard log levels.
  68. *
  69. *
  70. * See CakeLog::config() and CakeLog::write() for more information
  71. * on scopes
  72. *
  73. * @package Cake.Log
  74. */
  75. class CakeLog {
  76. /**
  77. * LogEngineCollection class
  78. *
  79. * @var LogEngineCollection
  80. */
  81. protected static $_Collection;
  82. /**
  83. * Default log levels as detailed in RFC 5424
  84. * http://tools.ietf.org/html/rfc5424
  85. *
  86. * @var array
  87. */
  88. protected static $_defaultLevels = array(
  89. 'emergency' => LOG_EMERG,
  90. 'alert' => LOG_ALERT,
  91. 'critical' => LOG_CRIT,
  92. 'error' => LOG_ERR,
  93. 'warning' => LOG_WARNING,
  94. 'notice' => LOG_NOTICE,
  95. 'info' => LOG_INFO,
  96. 'debug' => LOG_DEBUG,
  97. );
  98. /**
  99. * Active log levels for this instance.
  100. *
  101. * @var array
  102. */
  103. protected static $_levels;
  104. /**
  105. * Mapped log levels
  106. *
  107. * @var array
  108. */
  109. protected static $_levelMap;
  110. /**
  111. * initialize ObjectCollection
  112. *
  113. * @return void
  114. */
  115. protected static function _init() {
  116. self::$_levels = self::defaultLevels();
  117. self::$_Collection = new LogEngineCollection();
  118. }
  119. /**
  120. * Configure and add a new logging stream to CakeLog
  121. * You can use add loggers from app/Log/Engine use app.loggername, or any
  122. * plugin/Log/Engine using plugin.loggername.
  123. *
  124. * ### Usage:
  125. *
  126. * {{{
  127. * CakeLog::config('second_file', array(
  128. * 'engine' => 'File',
  129. * 'path' => '/var/logs/my_app/'
  130. * ));
  131. * }}}
  132. *
  133. * Will configure a FileLog instance to use the specified path.
  134. * All options that are not `engine` are passed onto the logging adapter,
  135. * and handled there. Any class can be configured as a logging
  136. * adapter as long as it implements the methods in CakeLogInterface.
  137. *
  138. * ### Logging levels
  139. *
  140. * When configuring loggers, you can set which levels a logger will handle.
  141. * This allows you to disable debug messages in production for example:
  142. *
  143. * {{{
  144. * CakeLog::config('default', array(
  145. * 'engine' => 'File',
  146. * 'path' => LOGS,
  147. * 'levels' => array('error', 'critical', 'alert', 'emergency')
  148. * ));
  149. * }}}
  150. *
  151. * The above logger would only log error messages or higher. Any
  152. * other log messages would be discarded.
  153. *
  154. * ### Logging scopes
  155. *
  156. * When configuring loggers you can define the active scopes the logger
  157. * is for. If defined only the listed scopes will be handled by the
  158. * logger. If you don't define any scopes an adapter will catch
  159. * all scopes that match the handled levels.
  160. *
  161. * {{{
  162. * CakeLog::config('payments', array(
  163. * 'engine' => 'File',
  164. * 'types' => array('info', 'error', 'warning'),
  165. * 'scopes' => array('payment', 'order')
  166. * ));
  167. * }}}
  168. *
  169. * The above logger will only capture log entries made in the
  170. * `payment` and `order` scopes. All other scopes including the
  171. * undefined scope will be ignored. Its important to remember that
  172. * when using scopes you must also define the `types` of log messages
  173. * that a logger will handle. Failing to do so will result in the logger
  174. * catching all log messages even if the scope is incorrect.
  175. *
  176. * @param string $key The keyname for this logger, used to remove the
  177. * logger later.
  178. * @param array $config Array of configuration information for the logger
  179. * @return boolean success of configuration.
  180. * @throws CakeLogException
  181. */
  182. public static function config($key, $config) {
  183. if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $key)) {
  184. throw new CakeLogException(__d('cake_dev', 'Invalid key name'));
  185. }
  186. if (empty($config['engine'])) {
  187. throw new CakeLogException(__d('cake_dev', 'Missing logger class name'));
  188. }
  189. if (empty(self::$_Collection)) {
  190. self::_init();
  191. }
  192. self::$_Collection->load($key, $config);
  193. return true;
  194. }
  195. /**
  196. * Returns the keynames of the currently active streams
  197. *
  198. * @return array Array of configured log streams.
  199. */
  200. public static function configured() {
  201. if (empty(self::$_Collection)) {
  202. self::_init();
  203. }
  204. return self::$_Collection->loaded();
  205. }
  206. /**
  207. * Gets/sets log levels
  208. *
  209. * Call this method without arguments, eg: `CakeLog::levels()` to obtain current
  210. * level configuration.
  211. *
  212. * To append additional level 'user0' and 'user1' to to default log levels:
  213. *
  214. * {{{
  215. * CakeLog::levels(array('user0, 'user1'));
  216. * // or
  217. * CakeLog::levels(array('user0, 'user1'), true);
  218. * }}}
  219. *
  220. * will result in:
  221. *
  222. * {{{
  223. * array(
  224. * 0 => 'emergency',
  225. * 1 => 'alert',
  226. * ...
  227. * 8 => 'user0',
  228. * 9 => 'user1',
  229. * );
  230. * }}}
  231. *
  232. * To set/replace existing configuration, pass an array with the second argument
  233. * set to false.
  234. *
  235. * {{{
  236. * CakeLog::levels(array('user0, 'user1'), false);
  237. * }}}
  238. *
  239. * will result in:
  240. *
  241. * {{{
  242. * array(
  243. * 0 => 'user0',
  244. * 1 => 'user1',
  245. * );
  246. * }}}
  247. *
  248. * @param array $levels array
  249. * @param boolean $append true to append, false to replace
  250. * @return array Active log levels
  251. */
  252. public static function levels($levels = array(), $append = true) {
  253. if (empty(self::$_Collection)) {
  254. self::_init();
  255. }
  256. if (empty($levels)) {
  257. return self::$_levels;
  258. }
  259. $levels = array_values($levels);
  260. if ($append) {
  261. self::$_levels = array_merge(self::$_levels, $levels);
  262. } else {
  263. self::$_levels = $levels;
  264. }
  265. self::$_levelMap = array_flip(self::$_levels);
  266. return self::$_levels;
  267. }
  268. /**
  269. * Reset log levels to the original value
  270. *
  271. * @return array Default log levels
  272. */
  273. public static function defaultLevels() {
  274. self::$_levelMap = self::$_defaultLevels;
  275. self::$_levels = array_flip(self::$_levelMap);
  276. return self::$_levels;
  277. }
  278. /**
  279. * Removes a stream from the active streams. Once a stream has been removed
  280. * it will no longer have messages sent to it.
  281. *
  282. * @param string $streamName Key name of a configured stream to remove.
  283. * @return void
  284. */
  285. public static function drop($streamName) {
  286. if (empty(self::$_Collection)) {
  287. self::_init();
  288. }
  289. self::$_Collection->unload($streamName);
  290. }
  291. /**
  292. * Checks whether $streamName is enabled
  293. *
  294. * @param string $streamName to check
  295. * @return boolean
  296. * @throws CakeLogException
  297. */
  298. public static function enabled($streamName) {
  299. if (empty(self::$_Collection)) {
  300. self::_init();
  301. }
  302. if (!isset(self::$_Collection->{$streamName})) {
  303. throw new CakeLogException(__d('cake_dev', 'Stream %s not found', $streamName));
  304. }
  305. return self::$_Collection->enabled($streamName);
  306. }
  307. /**
  308. * Enable stream. Streams that were previously disabled
  309. * can be re-enabled with this method.
  310. *
  311. * @param string $streamName to enable
  312. * @return void
  313. * @throws CakeLogException
  314. */
  315. public static function enable($streamName) {
  316. if (empty(self::$_Collection)) {
  317. self::_init();
  318. }
  319. if (!isset(self::$_Collection->{$streamName})) {
  320. throw new CakeLogException(__d('cake_dev', 'Stream %s not found', $streamName));
  321. }
  322. self::$_Collection->enable($streamName);
  323. }
  324. /**
  325. * Disable stream. Disabling a stream will
  326. * prevent that log stream from receiving any messages until
  327. * its re-enabled.
  328. *
  329. * @param string $streamName to disable
  330. * @return void
  331. * @throws CakeLogException
  332. */
  333. public static function disable($streamName) {
  334. if (empty(self::$_Collection)) {
  335. self::_init();
  336. }
  337. if (!isset(self::$_Collection->{$streamName})) {
  338. throw new CakeLogException(__d('cake_dev', 'Stream %s not found', $streamName));
  339. }
  340. self::$_Collection->disable($streamName);
  341. }
  342. /**
  343. * Gets the logging engine from the active streams.
  344. *
  345. * @see BaseLog
  346. * @param string $streamName Key name of a configured stream to get.
  347. * @return mixed instance of BaseLog or false if not found
  348. */
  349. public static function stream($streamName) {
  350. if (empty(self::$_Collection)) {
  351. self::_init();
  352. }
  353. if (!empty(self::$_Collection->{$streamName})) {
  354. return self::$_Collection->{$streamName};
  355. }
  356. return false;
  357. }
  358. /**
  359. * Writes the given message and type to all of the configured log adapters.
  360. * Configured adapters are passed both the $type and $message variables. $type
  361. * is one of the following strings/values.
  362. *
  363. * ### Types:
  364. *
  365. * - LOG_EMERG => 'emergency',
  366. * - LOG_ALERT => 'alert',
  367. * - LOG_CRIT => 'critical',
  368. * - `LOG_ERR` => 'error',
  369. * - `LOG_WARNING` => 'warning',
  370. * - `LOG_NOTICE` => 'notice',
  371. * - `LOG_INFO` => 'info',
  372. * - `LOG_DEBUG` => 'debug',
  373. *
  374. * ### Usage:
  375. *
  376. * Write a message to the 'warning' log:
  377. *
  378. * `CakeLog::write('warning', 'Stuff is broken here');`
  379. *
  380. * @param integer|string $type Type of message being written. When value is an integer
  381. * or a string matching the recognized levels, then it will
  382. * be treated log levels. Otherwise it's treated as scope.
  383. * @param string $message Message content to log
  384. * @param string|array $scope The scope(s) a log message is being created in.
  385. * See CakeLog::config() for more information on logging scopes.
  386. * @return boolean Success
  387. */
  388. public static function write($type, $message, $scope = array()) {
  389. if (empty(self::$_Collection)) {
  390. self::_init();
  391. }
  392. if (is_int($type) && isset(self::$_levels[$type])) {
  393. $type = self::$_levels[$type];
  394. }
  395. if (is_string($type) && empty($scope) && !in_array($type, self::$_levels)) {
  396. $scope = $type;
  397. }
  398. $logged = false;
  399. foreach (self::$_Collection->enabled() as $streamName) {
  400. $logger = self::$_Collection->{$streamName};
  401. $types = $scopes = $config = array();
  402. if (method_exists($logger, 'config')) {
  403. $config = $logger->config();
  404. }
  405. if (isset($config['types'])) {
  406. $types = $config['types'];
  407. }
  408. if (isset($config['scopes'])) {
  409. $scopes = $config['scopes'];
  410. }
  411. $inScope = (count(array_intersect((array)$scope, $scopes)) > 0);
  412. $correctLevel = in_array($type, $types);
  413. if (
  414. // No config is a catch all (bc mode)
  415. (empty($types) && empty($scopes)) ||
  416. // BC layer for mixing scope & level
  417. (in_array($type, $scopes)) ||
  418. // no scopes, but has level
  419. (empty($scopes) && $correctLevel) ||
  420. // exact scope + level
  421. ($correctLevel && $inScope)
  422. ) {
  423. $logger->write($type, $message);
  424. $logged = true;
  425. }
  426. }
  427. return $logged;
  428. }
  429. /**
  430. * Convenience method to log emergency messages
  431. *
  432. * @param string $message log message
  433. * @param string|array $scope The scope(s) a log message is being created in.
  434. * See CakeLog::config() for more information on logging scopes.
  435. * @return boolean Success
  436. */
  437. public static function emergency($message, $scope = array()) {
  438. return self::write(self::$_levelMap['emergency'], $message, $scope);
  439. }
  440. /**
  441. * Convenience method to log alert messages
  442. *
  443. * @param string $message log message
  444. * @param string|array $scope The scope(s) a log message is being created in.
  445. * See CakeLog::config() for more information on logging scopes.
  446. * @return boolean Success
  447. */
  448. public static function alert($message, $scope = array()) {
  449. return self::write(self::$_levelMap['alert'], $message, $scope);
  450. }
  451. /**
  452. * Convenience method to log critical messages
  453. *
  454. * @param string $message log message
  455. * @param string|array $scope The scope(s) a log message is being created in.
  456. * See CakeLog::config() for more information on logging scopes.
  457. * @return boolean Success
  458. */
  459. public static function critical($message, $scope = array()) {
  460. return self::write(self::$_levelMap['critical'], $message, $scope);
  461. }
  462. /**
  463. * Convenience method to log error messages
  464. *
  465. * @param string $message log message
  466. * @param string|array $scope The scope(s) a log message is being created in.
  467. * See CakeLog::config() for more information on logging scopes.
  468. * @return boolean Success
  469. */
  470. public static function error($message, $scope = array()) {
  471. return self::write(self::$_levelMap['error'], $message, $scope);
  472. }
  473. /**
  474. * Convenience method to log warning messages
  475. *
  476. * @param string $message log message
  477. * @param string|array $scope The scope(s) a log message is being created in.
  478. * See CakeLog::config() for more information on logging scopes.
  479. * @return boolean Success
  480. */
  481. public static function warning($message, $scope = array()) {
  482. return self::write(self::$_levelMap['warning'], $message, $scope);
  483. }
  484. /**
  485. * Convenience method to log notice messages
  486. *
  487. * @param string $message log message
  488. * @param string|array $scope The scope(s) a log message is being created in.
  489. * See CakeLog::config() for more information on logging scopes.
  490. * @return boolean Success
  491. */
  492. public static function notice($message, $scope = array()) {
  493. return self::write(self::$_levelMap['notice'], $message, $scope);
  494. }
  495. /**
  496. * Convenience method to log debug messages
  497. *
  498. * @param string $message log message
  499. * @param string|array $scope The scope(s) a log message is being created in.
  500. * See CakeLog::config() for more information on logging scopes.
  501. * @return boolean Success
  502. */
  503. public static function debug($message, $scope = array()) {
  504. return self::write(self::$_levelMap['debug'], $message, $scope);
  505. }
  506. /**
  507. * Convenience method to log info messages
  508. *
  509. * @param string $message log message
  510. * @param string|array $scope The scope(s) a log message is being created in.
  511. * See CakeLog::config() for more information on logging scopes.
  512. * @return boolean Success
  513. */
  514. public static function info($message, $scope = array()) {
  515. return self::write(self::$_levelMap['info'], $message, $scope);
  516. }
  517. }