CakeLog.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  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' => 'FileLog'));
  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' => 'FileLog',
  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. * 'scopes' => array('payment', 'order')
  165. * ));
  166. * }}}
  167. *
  168. * The above logger will only capture log entries made in the
  169. * `payment` and `order` scopes. All other scopes including the
  170. * undefined scope will be ignored. Its important to remember that
  171. * when using scopes you must also define the `types` of log messages
  172. * that a logger will handle. Failing to do so will result in the logger
  173. * catching all log messages even if the scope is incorrect.
  174. *
  175. * @param string $key The keyname for this logger, used to remove the
  176. * logger later.
  177. * @param array $config Array of configuration information for the logger
  178. * @return boolean success of configuration.
  179. * @throws CakeLogException
  180. */
  181. public static function config($key, $config) {
  182. if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $key)) {
  183. throw new CakeLogException(__d('cake_dev', 'Invalid key name'));
  184. }
  185. if (empty($config['engine'])) {
  186. throw new CakeLogException(__d('cake_dev', 'Missing logger classname'));
  187. }
  188. if (empty(self::$_Collection)) {
  189. self::_init();
  190. }
  191. self::$_Collection->load($key, $config);
  192. return true;
  193. }
  194. /**
  195. * Returns the keynames of the currently active streams
  196. *
  197. * @return array Array of configured log streams.
  198. */
  199. public static function configured() {
  200. if (empty(self::$_Collection)) {
  201. self::_init();
  202. }
  203. return self::$_Collection->loaded();
  204. }
  205. /**
  206. * Gets/sets log levels
  207. *
  208. * Call this method without arguments, eg: `CakeLog::levels()` to obtain current
  209. * level configuration.
  210. *
  211. * To append additional level 'user0' and 'user1' to to default log levels:
  212. *
  213. * {{{
  214. * CakeLog::levels(array('user0, 'user1'));
  215. * // or
  216. * CakeLog::levels(array('user0, 'user1'), true);
  217. * }}}
  218. *
  219. * will result in:
  220. *
  221. * {{{
  222. * array(
  223. * 0 => 'emergency',
  224. * 1 => 'alert',
  225. * ...
  226. * 8 => 'user0',
  227. * 9 => 'user1',
  228. * );
  229. * }}}
  230. *
  231. * To set/replace existing configuration, pass an array with the second argument
  232. * set to false.
  233. *
  234. * {{{
  235. * CakeLog::levels(array('user0, 'user1'), false);
  236. * }}}
  237. *
  238. * will result in:
  239. *
  240. * {{{
  241. * array(
  242. * 0 => 'user0',
  243. * 1 => 'user1',
  244. * );
  245. * }}}
  246. *
  247. * @param array $levels array
  248. * @param bool $append true to append, false to replace
  249. * @return array active log levels
  250. */
  251. public static function levels($levels = array(), $append = true) {
  252. if (empty(self::$_Collection)) {
  253. self::_init();
  254. }
  255. if (empty($levels)) {
  256. return self::$_levels;
  257. }
  258. $levels = array_values($levels);
  259. if ($append) {
  260. self::$_levels = array_merge(self::$_levels, $levels);
  261. } else {
  262. self::$_levels = $levels;
  263. }
  264. self::$_levelMap = array_flip(self::$_levels);
  265. return self::$_levels;
  266. }
  267. /**
  268. * Reset log levels to the original value
  269. *
  270. * @return array default log levels
  271. */
  272. public static function defaultLevels() {
  273. self::$_levelMap = self::$_defaultLevels;
  274. self::$_levels = array_flip(self::$_levelMap);
  275. return self::$_levels;
  276. }
  277. /**
  278. * Removes a stream from the active streams. Once a stream has been removed
  279. * it will no longer have messages sent to it.
  280. *
  281. * @param string $streamName Key name of a configured stream to remove.
  282. * @return void
  283. */
  284. public static function drop($streamName) {
  285. if (empty(self::$_Collection)) {
  286. self::_init();
  287. }
  288. self::$_Collection->unload($streamName);
  289. }
  290. /**
  291. * Checks whether $streamName is enabled
  292. *
  293. * @param string $streamName to check
  294. * @return bool
  295. * @throws CakeLogException
  296. */
  297. public static function enabled($streamName) {
  298. if (empty(self::$_Collection)) {
  299. self::_init();
  300. }
  301. if (!isset(self::$_Collection->{$streamName})) {
  302. throw new CakeLogException(__d('cake_dev', 'Stream %s not found', $streamName));
  303. }
  304. return self::$_Collection->enabled($streamName);
  305. }
  306. /**
  307. * Enable stream. Streams that were previously disabled
  308. * can be re-enabled with this method.
  309. *
  310. * @param string $streamName to enable
  311. * @return void
  312. * @throws CakeLogException
  313. */
  314. public static function enable($streamName) {
  315. if (empty(self::$_Collection)) {
  316. self::_init();
  317. }
  318. if (!isset(self::$_Collection->{$streamName})) {
  319. throw new CakeLogException(__d('cake_dev', 'Stream %s not found', $streamName));
  320. }
  321. self::$_Collection->enable($streamName);
  322. }
  323. /**
  324. * Disable stream. Disabling a stream will
  325. * prevent that log stream from receiving any messages until
  326. * its re-enabled.
  327. *
  328. * @param string $streamName to disable
  329. * @return void
  330. * @throws CakeLogException
  331. */
  332. public static function disable($streamName) {
  333. if (empty(self::$_Collection)) {
  334. self::_init();
  335. }
  336. if (!isset(self::$_Collection->{$streamName})) {
  337. throw new CakeLogException(__d('cake_dev', 'Stream %s not found', $streamName));
  338. }
  339. self::$_Collection->disable($streamName);
  340. }
  341. /**
  342. * Gets the logging engine from the active streams.
  343. *
  344. * @see BaseLog
  345. * @param string $streamName Key name of a configured stream to get.
  346. * @return mixed instance of BaseLog or false if not found
  347. */
  348. public static function stream($streamName) {
  349. if (empty(self::$_Collection)) {
  350. self::_init();
  351. }
  352. if (!empty(self::$_Collection->{$streamName})) {
  353. return self::$_Collection->{$streamName};
  354. }
  355. return false;
  356. }
  357. /**
  358. * Configures the automatic/default stream a FileLog.
  359. *
  360. * @return void
  361. */
  362. protected static function _autoConfig() {
  363. self::$_Collection->load('default', array(
  364. 'engine' => 'FileLog',
  365. 'path' => LOGS,
  366. ));
  367. }
  368. /**
  369. * Writes the given message and type to all of the configured log adapters.
  370. * Configured adapters are passed both the $type and $message variables. $type
  371. * is one of the following strings/values.
  372. *
  373. * ### Types:
  374. *
  375. * - LOG_EMERG => 'emergency',
  376. * - LOG_ALERT => 'alert',
  377. * - LOG_CRIT => 'critical',
  378. * - `LOG_ERR` => 'error',
  379. * - `LOG_WARNING` => 'warning',
  380. * - `LOG_NOTICE` => 'notice',
  381. * - `LOG_INFO` => 'info',
  382. * - `LOG_DEBUG` => 'debug',
  383. *
  384. * ### Usage:
  385. *
  386. * Write a message to the 'warning' log:
  387. *
  388. * `CakeLog::write('warning', 'Stuff is broken here');`
  389. *
  390. * @param integer|string $type Type of message being written. When value is an integer
  391. * or a string matching the recognized levels, then it will
  392. * be treated log levels. Otherwise it's treated as scope.
  393. * @param string $message Message content to log
  394. * @param string|array $scope The scope(s) a log message is being created in.
  395. * See CakeLog::config() for more information on logging scopes.
  396. * @return boolean Success
  397. */
  398. public static function write($type, $message, $scope = array()) {
  399. if (empty(self::$_Collection)) {
  400. self::_init();
  401. }
  402. if (is_int($type) && isset(self::$_levels[$type])) {
  403. $type = self::$_levels[$type];
  404. }
  405. if (is_string($type) && empty($scope) && !in_array($type, self::$_levels)) {
  406. $scope = $type;
  407. }
  408. $logged = false;
  409. foreach (self::$_Collection->enabled() as $streamName) {
  410. $logger = self::$_Collection->{$streamName};
  411. $types = $scopes = $config = array();
  412. if (method_exists($logger, 'config')) {
  413. $config = $logger->config();
  414. }
  415. if (isset($config['types'])) {
  416. $types = $config['types'];
  417. }
  418. if (isset($config['scopes'])) {
  419. $scopes = $config['scopes'];
  420. }
  421. $inScope = (count(array_intersect((array)$scope, $scopes)) > 0);
  422. $correctLevel = in_array($type, $types);
  423. if (
  424. // No config is a catch all (bc mode)
  425. (empty($types) && empty($scopes)) ||
  426. // BC layer for mixing scope & level
  427. (in_array($type, $scopes)) ||
  428. // no scopes, but has level
  429. (empty($scopes) && $correctLevel) ||
  430. // exact scope + level
  431. ($correctLevel && $inScope)
  432. ) {
  433. $logger->write($type, $message);
  434. $logged = true;
  435. }
  436. }
  437. if (!$logged) {
  438. self::_autoConfig();
  439. self::stream('default')->write($type, $message);
  440. }
  441. return true;
  442. }
  443. /**
  444. * Convenience method to log emergency messages
  445. *
  446. * @param string $message log message
  447. * @param string|array $scope The scope(s) a log message is being created in.
  448. * See CakeLog::config() for more information on logging scopes.
  449. * @return boolean Success
  450. */
  451. public static function emergency($message, $scope = array()) {
  452. return self::write(self::$_levelMap['emergency'], $message, $scope);
  453. }
  454. /**
  455. * Convenience method to log alert messages
  456. *
  457. * @param string $message log message
  458. * @param string|array $scope The scope(s) a log message is being created in.
  459. * See CakeLog::config() for more information on logging scopes.
  460. * @return boolean Success
  461. */
  462. public static function alert($message, $scope = array()) {
  463. return self::write(self::$_levelMap['alert'], $message, $scope);
  464. }
  465. /**
  466. * Convenience method to log critical messages
  467. *
  468. * @param string $message log message
  469. * @param string|array $scope The scope(s) a log message is being created in.
  470. * See CakeLog::config() for more information on logging scopes.
  471. * @return boolean Success
  472. */
  473. public static function critical($message, $scope = array()) {
  474. return self::write(self::$_levelMap['critical'], $message, $scope);
  475. }
  476. /**
  477. * Convenience method to log error messages
  478. *
  479. * @param string $message log message
  480. * @param string|array $scope The scope(s) a log message is being created in.
  481. * See CakeLog::config() for more information on logging scopes.
  482. * @return boolean Success
  483. */
  484. public static function error($message, $scope = array()) {
  485. return self::write(self::$_levelMap['error'], $message, $scope);
  486. }
  487. /**
  488. * Convenience method to log warning messages
  489. *
  490. * @param string $message log message
  491. * @param string|array $scope The scope(s) a log message is being created in.
  492. * See CakeLog::config() for more information on logging scopes.
  493. * @return boolean Success
  494. */
  495. public static function warning($message, $scope = array()) {
  496. return self::write(self::$_levelMap['warning'], $message, $scope);
  497. }
  498. /**
  499. * Convenience method to log notice messages
  500. *
  501. * @param string $message log message
  502. * @param string|array $scope The scope(s) a log message is being created in.
  503. * See CakeLog::config() for more information on logging scopes.
  504. * @return boolean Success
  505. */
  506. public static function notice($message, $scope = array()) {
  507. return self::write(self::$_levelMap['notice'], $message, $scope);
  508. }
  509. /**
  510. * Convenience method to log debug messages
  511. *
  512. * @param string $message log message
  513. * @param string|array $scope The scope(s) a log message is being created in.
  514. * See CakeLog::config() for more information on logging scopes.
  515. * @return boolean Success
  516. */
  517. public static function debug($message, $scope = array()) {
  518. return self::write(self::$_levelMap['debug'], $message, $scope);
  519. }
  520. /**
  521. * Convenience method to log info messages
  522. *
  523. * @param string $message log message
  524. * @param string|array $scope The scope(s) a log message is being created in.
  525. * See CakeLog::config() for more information on logging scopes.
  526. * @return boolean Success
  527. */
  528. public static function info($message, $scope = array()) {
  529. return self::write(self::$_levelMap['info'], $message, $scope);
  530. }
  531. }