Log.php 13 KB

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