CakeLog.php 15 KB

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