PageRenderTime 43ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/library/Zend/Log.php

https://bitbucket.org/michalmatoga/ebpl
PHP | 634 lines | 468 code | 41 blank | 125 comment | 25 complexity | 89aa4f953a394d0977d1a79c59b65215 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Log
  17. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id: Log.php 24703 2012-03-29 09:52:39Z andries $
  20. */
  21. /**
  22. * @category Zend
  23. * @package Zend_Log
  24. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  25. * @license http://framework.zend.com/license/new-bsd New BSD License
  26. * @version $Id: Log.php 24703 2012-03-29 09:52:39Z andries $
  27. */
  28. class Zend_Log
  29. {
  30. const EMERG = 0; // Emergency: system is unusable
  31. const ALERT = 1; // Alert: action must be taken immediately
  32. const CRIT = 2; // Critical: critical conditions
  33. const ERR = 3; // Error: error conditions
  34. const WARN = 4; // Warning: warning conditions
  35. const NOTICE = 5; // Notice: normal but significant condition
  36. const INFO = 6; // Informational: informational messages
  37. const DEBUG = 7; // Debug: debug messages
  38. /**
  39. * @var array of priorities where the keys are the
  40. * priority numbers and the values are the priority names
  41. */
  42. protected $_priorities = array();
  43. /**
  44. * @var array of Zend_Log_Writer_Abstract
  45. */
  46. protected $_writers = array();
  47. /**
  48. * @var array of Zend_Log_Filter_Interface
  49. */
  50. protected $_filters = array();
  51. /**
  52. * @var array of extra log event
  53. */
  54. protected $_extras = array();
  55. /**
  56. *
  57. * @var string
  58. */
  59. protected $_defaultWriterNamespace = 'Zend_Log_Writer';
  60. /**
  61. *
  62. * @var string
  63. */
  64. protected $_defaultFilterNamespace = 'Zend_Log_Filter';
  65. /**
  66. *
  67. * @var string
  68. */
  69. protected $_defaultFormatterNamespace = 'Zend_Log_Formatter';
  70. /**
  71. *
  72. * @var callback
  73. */
  74. protected $_origErrorHandler = null;
  75. /**
  76. *
  77. * @var boolean
  78. */
  79. protected $_registeredErrorHandler = false;
  80. /**
  81. *
  82. * @var array|boolean
  83. */
  84. protected $_errorHandlerMap = false;
  85. /**
  86. *
  87. * @var string
  88. */
  89. protected $_timestampFormat = 'c';
  90. /**
  91. * Class constructor. Create a new logger
  92. *
  93. * @param Zend_Log_Writer_Abstract|null $writer default writer
  94. * @return void
  95. */
  96. public function __construct(Zend_Log_Writer_Abstract $writer = null)
  97. {
  98. $r = new ReflectionClass($this);
  99. $this->_priorities = array_flip($r->getConstants());
  100. if ($writer !== null) {
  101. $this->addWriter($writer);
  102. }
  103. }
  104. /**
  105. * Factory to construct the logger and one or more writers
  106. * based on the configuration array
  107. *
  108. * @param array|Zend_Config Array or instance of Zend_Config
  109. * @return Zend_Log
  110. * @throws Zend_Log_Exception
  111. */
  112. static public function factory($config = array())
  113. {
  114. if ($config instanceof Zend_Config) {
  115. $config = $config->toArray();
  116. }
  117. if (!is_array($config) || empty($config)) {
  118. /** @see Zend_Log_Exception */
  119. require_once 'Zend/Log/Exception.php';
  120. throw new Zend_Log_Exception('Configuration must be an array or instance of Zend_Config');
  121. }
  122. $log = new self;
  123. if (array_key_exists('timestampFormat', $config)) {
  124. if (null != $config['timestampFormat'] && '' != $config['timestampFormat']) {
  125. $log->setTimestampFormat($config['timestampFormat']);
  126. }
  127. unset($config['timestampFormat']);
  128. }
  129. if (!is_array(current($config))) {
  130. $log->addWriter(current($config));
  131. } else {
  132. foreach($config as $writer) {
  133. $log->addWriter($writer);
  134. }
  135. }
  136. return $log;
  137. }
  138. /**
  139. * Construct a writer object based on a configuration array
  140. *
  141. * @param array $spec config array with writer spec
  142. * @return Zend_Log_Writer_Abstract
  143. * @throws Zend_Log_Exception
  144. */
  145. protected function _constructWriterFromConfig($config)
  146. {
  147. $writer = $this->_constructFromConfig('writer', $config, $this->_defaultWriterNamespace);
  148. if (!$writer instanceof Zend_Log_Writer_Abstract) {
  149. $writerName = is_object($writer)
  150. ? get_class($writer)
  151. : 'The specified writer';
  152. /** @see Zend_Log_Exception */
  153. require_once 'Zend/Log/Exception.php';
  154. throw new Zend_Log_Exception("{$writerName} does not extend Zend_Log_Writer_Abstract!");
  155. }
  156. if (isset($config['filterName'])) {
  157. $filter = $this->_constructFilterFromConfig($config);
  158. $writer->addFilter($filter);
  159. }
  160. if (isset($config['formatterName'])) {
  161. $formatter = $this->_constructFormatterFromConfig($config);
  162. $writer->setFormatter($formatter);
  163. }
  164. return $writer;
  165. }
  166. /**
  167. * Construct filter object from configuration array or Zend_Config object
  168. *
  169. * @param array|Zend_Config $config Zend_Config or Array
  170. * @return Zend_Log_Filter_Interface
  171. * @throws Zend_Log_Exception
  172. */
  173. protected function _constructFilterFromConfig($config)
  174. {
  175. $filter = $this->_constructFromConfig('filter', $config, $this->_defaultFilterNamespace);
  176. if (!$filter instanceof Zend_Log_Filter_Interface) {
  177. $filterName = is_object($filter)
  178. ? get_class($filter)
  179. : 'The specified filter';
  180. /** @see Zend_Log_Exception */
  181. require_once 'Zend/Log/Exception.php';
  182. throw new Zend_Log_Exception("{$filterName} does not implement Zend_Log_Filter_Interface");
  183. }
  184. return $filter;
  185. }
  186. /**
  187. * Construct formatter object from configuration array or Zend_Config object
  188. *
  189. * @param array|Zend_Config $config Zend_Config or Array
  190. * @return Zend_Log_Formatter_Interface
  191. * @throws Zend_Log_Exception
  192. */
  193. protected function _constructFormatterFromConfig($config)
  194. {
  195. $formatter = $this->_constructFromConfig('formatter', $config, $this->_defaultFormatterNamespace);
  196. if (!$formatter instanceof Zend_Log_Formatter_Interface) {
  197. $formatterName = is_object($formatter)
  198. ? get_class($formatter)
  199. : 'The specified formatter';
  200. /** @see Zend_Log_Exception */
  201. require_once 'Zend/Log/Exception.php';
  202. throw new Zend_Log_Exception($formatterName . ' does not implement Zend_Log_Formatter_Interface');
  203. }
  204. return $formatter;
  205. }
  206. /**
  207. * Construct a filter or writer from config
  208. *
  209. * @param string $type 'writer' of 'filter'
  210. * @param mixed $config Zend_Config or Array
  211. * @param string $namespace
  212. * @return object
  213. * @throws Zend_Log_Exception
  214. */
  215. protected function _constructFromConfig($type, $config, $namespace)
  216. {
  217. if ($config instanceof Zend_Config) {
  218. $config = $config->toArray();
  219. }
  220. if (!is_array($config) || empty($config)) {
  221. require_once 'Zend/Log/Exception.php';
  222. throw new Zend_Log_Exception(
  223. 'Configuration must be an array or instance of Zend_Config'
  224. );
  225. }
  226. $params = isset($config[ $type .'Params' ]) ? $config[ $type .'Params' ] : array();
  227. $className = $this->getClassName($config, $type, $namespace);
  228. if (!class_exists($className)) {
  229. require_once 'Zend/Loader.php';
  230. Zend_Loader::loadClass($className);
  231. }
  232. $reflection = new ReflectionClass($className);
  233. if (!$reflection->implementsInterface('Zend_Log_FactoryInterface')) {
  234. require_once 'Zend/Log/Exception.php';
  235. throw new Zend_Log_Exception(
  236. $className . ' does not implement Zend_Log_FactoryInterface and can not be constructed from config.'
  237. );
  238. }
  239. return call_user_func(array($className, 'factory'), $params);
  240. }
  241. /**
  242. * Get the writer or filter full classname
  243. *
  244. * @param array $config
  245. * @param string $type filter|writer
  246. * @param string $defaultNamespace
  247. * @return string full classname
  248. * @throws Zend_Log_Exception
  249. */
  250. protected function getClassName($config, $type, $defaultNamespace)
  251. {
  252. if (!isset($config[$type . 'Name'])) {
  253. require_once 'Zend/Log/Exception.php';
  254. throw new Zend_Log_Exception("Specify {$type}Name in the configuration array");
  255. }
  256. $className = $config[$type . 'Name'];
  257. $namespace = $defaultNamespace;
  258. if (isset($config[$type . 'Namespace'])) {
  259. $namespace = $config[$type . 'Namespace'];
  260. }
  261. // PHP >= 5.3.0 namespace given?
  262. if (substr($namespace, -1) == '\\') {
  263. return $namespace . $className;
  264. }
  265. // emtpy namespace given?
  266. if (strlen($namespace) === 0) {
  267. return $className;
  268. }
  269. return $namespace . '_' . $className;
  270. }
  271. /**
  272. * Packs message and priority into Event array
  273. *
  274. * @param string $message Message to log
  275. * @param integer $priority Priority of message
  276. * @return array Event array
  277. */
  278. protected function _packEvent($message, $priority)
  279. {
  280. return array_merge(array(
  281. 'timestamp' => date($this->_timestampFormat),
  282. 'message' => $message,
  283. 'priority' => $priority,
  284. 'priorityName' => $this->_priorities[$priority]
  285. ),
  286. $this->_extras
  287. );
  288. }
  289. /**
  290. * Class destructor. Shutdown log writers
  291. *
  292. * @return void
  293. */
  294. public function __destruct()
  295. {
  296. foreach($this->_writers as $writer) {
  297. $writer->shutdown();
  298. }
  299. }
  300. /**
  301. * Undefined method handler allows a shortcut:
  302. * $log->priorityName('message')
  303. * instead of
  304. * $log->log('message', Zend_Log::PRIORITY_NAME)
  305. *
  306. * @param string $method priority name
  307. * @param string $params message to log
  308. * @return void
  309. * @throws Zend_Log_Exception
  310. */
  311. public function __call($method, $params)
  312. {
  313. $priority = strtoupper($method);
  314. if (($priority = array_search($priority, $this->_priorities)) !== false) {
  315. switch (count($params)) {
  316. case 0:
  317. /** @see Zend_Log_Exception */
  318. require_once 'Zend/Log/Exception.php';
  319. throw new Zend_Log_Exception('Missing log message');
  320. case 1:
  321. $message = array_shift($params);
  322. $extras = null;
  323. break;
  324. default:
  325. $message = array_shift($params);
  326. $extras = array_shift($params);
  327. break;
  328. }
  329. $this->log($message, $priority, $extras);
  330. } else {
  331. /** @see Zend_Log_Exception */
  332. require_once 'Zend/Log/Exception.php';
  333. throw new Zend_Log_Exception('Bad log priority');
  334. }
  335. }
  336. /**
  337. * Log a message at a priority
  338. *
  339. * @param string $message Message to log
  340. * @param integer $priority Priority of message
  341. * @param mixed $extras Extra information to log in event
  342. * @return void
  343. * @throws Zend_Log_Exception
  344. */
  345. public function log($message, $priority, $extras = null)
  346. {
  347. // sanity checks
  348. if (empty($this->_writers)) {
  349. /** @see Zend_Log_Exception */
  350. require_once 'Zend/Log/Exception.php';
  351. throw new Zend_Log_Exception('No writers were added');
  352. }
  353. if (! isset($this->_priorities[$priority])) {
  354. /** @see Zend_Log_Exception */
  355. require_once 'Zend/Log/Exception.php';
  356. throw new Zend_Log_Exception('Bad log priority');
  357. }
  358. // pack into event required by filters and writers
  359. $event = $this->_packEvent($message, $priority);
  360. // Check to see if any extra information was passed
  361. if (!empty($extras)) {
  362. $info = array();
  363. if (is_array($extras)) {
  364. foreach ($extras as $key => $value) {
  365. if (is_string($key)) {
  366. $event[$key] = $value;
  367. } else {
  368. $info[] = $value;
  369. }
  370. }
  371. } else {
  372. $info = $extras;
  373. }
  374. if (!empty($info)) {
  375. $event['info'] = $info;
  376. }
  377. }
  378. // abort if rejected by the global filters
  379. foreach ($this->_filters as $filter) {
  380. if (! $filter->accept($event)) {
  381. return;
  382. }
  383. }
  384. // send to each writer
  385. foreach ($this->_writers as $writer) {
  386. $writer->write($event);
  387. }
  388. }
  389. /**
  390. * Add a custom priority
  391. *
  392. * @param string $name Name of priority
  393. * @param integer $priority Numeric priority
  394. * @throws Zend_Log_Exception
  395. */
  396. public function addPriority($name, $priority)
  397. {
  398. // Priority names must be uppercase for predictability.
  399. $name = strtoupper($name);
  400. if (isset($this->_priorities[$priority])
  401. || false !== array_search($name, $this->_priorities)) {
  402. /** @see Zend_Log_Exception */
  403. require_once 'Zend/Log/Exception.php';
  404. throw new Zend_Log_Exception('Existing priorities cannot be overwritten');
  405. }
  406. $this->_priorities[$priority] = $name;
  407. return $this;
  408. }
  409. /**
  410. * Add a filter that will be applied before all log writers.
  411. * Before a message will be received by any of the writers, it
  412. * must be accepted by all filters added with this method.
  413. *
  414. * @param int|Zend_Config|array|Zend_Log_Filter_Interface $filter
  415. * @return Zend_Log
  416. * @throws Zend_Log_Exception
  417. */
  418. public function addFilter($filter)
  419. {
  420. if (is_int($filter)) {
  421. /** @see Zend_Log_Filter_Priority */
  422. require_once 'Zend/Log/Filter/Priority.php';
  423. $filter = new Zend_Log_Filter_Priority($filter);
  424. } elseif ($filter instanceof Zend_Config || is_array($filter)) {
  425. $filter = $this->_constructFilterFromConfig($filter);
  426. } elseif(! $filter instanceof Zend_Log_Filter_Interface) {
  427. /** @see Zend_Log_Exception */
  428. require_once 'Zend/Log/Exception.php';
  429. throw new Zend_Log_Exception('Invalid filter provided');
  430. }
  431. $this->_filters[] = $filter;
  432. return $this;
  433. }
  434. /**
  435. * Add a writer. A writer is responsible for taking a log
  436. * message and writing it out to storage.
  437. *
  438. * @param mixed $writer Zend_Log_Writer_Abstract or Config array
  439. * @return Zend_Log
  440. */
  441. public function addWriter($writer)
  442. {
  443. if (is_array($writer) || $writer instanceof Zend_Config) {
  444. $writer = $this->_constructWriterFromConfig($writer);
  445. }
  446. if (!$writer instanceof Zend_Log_Writer_Abstract) {
  447. /** @see Zend_Log_Exception */
  448. require_once 'Zend/Log/Exception.php';
  449. throw new Zend_Log_Exception(
  450. 'Writer must be an instance of Zend_Log_Writer_Abstract'
  451. . ' or you should pass a configuration array'
  452. );
  453. }
  454. $this->_writers[] = $writer;
  455. return $this;
  456. }
  457. /**
  458. * Set an extra item to pass to the log writers.
  459. *
  460. * @param string $name Name of the field
  461. * @param string $value Value of the field
  462. * @return Zend_Log
  463. */
  464. public function setEventItem($name, $value)
  465. {
  466. $this->_extras = array_merge($this->_extras, array($name => $value));
  467. return $this;
  468. }
  469. /**
  470. * Register Logging system as an error handler to log php errors
  471. * Note: it still calls the original error handler if set_error_handler is able to return it.
  472. *
  473. * Errors will be mapped as:
  474. * E_NOTICE, E_USER_NOTICE => NOTICE
  475. * E_WARNING, E_CORE_WARNING, E_USER_WARNING => WARN
  476. * E_ERROR, E_USER_ERROR, E_CORE_ERROR, E_RECOVERABLE_ERROR => ERR
  477. * E_DEPRECATED, E_STRICT, E_USER_DEPRECATED => DEBUG
  478. * (unknown/other) => INFO
  479. *
  480. * @link http://www.php.net/manual/en/function.set-error-handler.php Custom error handler
  481. *
  482. * @return Zend_Log
  483. */
  484. public function registerErrorHandler()
  485. {
  486. // Only register once. Avoids loop issues if it gets registered twice.
  487. if ($this->_registeredErrorHandler) {
  488. return $this;
  489. }
  490. $this->_origErrorHandler = set_error_handler(array($this, 'errorHandler'));
  491. // Contruct a default map of phpErrors to Zend_Log priorities.
  492. // Some of the errors are uncatchable, but are included for completeness
  493. $this->_errorHandlerMap = array(
  494. E_NOTICE => Zend_Log::NOTICE,
  495. E_USER_NOTICE => Zend_Log::NOTICE,
  496. E_WARNING => Zend_Log::WARN,
  497. E_CORE_WARNING => Zend_Log::WARN,
  498. E_USER_WARNING => Zend_Log::WARN,
  499. E_ERROR => Zend_Log::ERR,
  500. E_USER_ERROR => Zend_Log::ERR,
  501. E_CORE_ERROR => Zend_Log::ERR,
  502. E_RECOVERABLE_ERROR => Zend_Log::ERR,
  503. E_STRICT => Zend_Log::DEBUG,
  504. );
  505. // PHP 5.3.0+
  506. if (defined('E_DEPRECATED')) {
  507. $this->_errorHandlerMap['E_DEPRECATED'] = Zend_Log::DEBUG;
  508. }
  509. if (defined('E_USER_DEPRECATED')) {
  510. $this->_errorHandlerMap['E_USER_DEPRECATED'] = Zend_Log::DEBUG;
  511. }
  512. $this->_registeredErrorHandler = true;
  513. return $this;
  514. }
  515. /**
  516. * Error Handler will convert error into log message, and then call the original error handler
  517. *
  518. * @link http://www.php.net/manual/en/function.set-error-handler.php Custom error handler
  519. * @param int $errno
  520. * @param string $errstr
  521. * @param string $errfile
  522. * @param int $errline
  523. * @param array $errcontext
  524. * @return boolean
  525. */
  526. public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
  527. {
  528. $errorLevel = error_reporting();
  529. if ($errorLevel && $errno) {
  530. if (isset($this->_errorHandlerMap[$errno])) {
  531. $priority = $this->_errorHandlerMap[$errno];
  532. } else {
  533. $priority = Zend_Log::INFO;
  534. }
  535. $this->log($errstr, $priority, array('errno'=>$errno, 'file'=>$errfile, 'line'=>$errline, 'context'=>$errcontext));
  536. }
  537. if ($this->_origErrorHandler !== null) {
  538. return call_user_func($this->_origErrorHandler, $errno, $errstr, $errfile, $errline, $errcontext);
  539. }
  540. return false;
  541. }
  542. /**
  543. * Set timestamp format for log entries.
  544. *
  545. * @param string $format
  546. * @return Zend_Log
  547. */
  548. public function setTimestampFormat($format)
  549. {
  550. $this->_timestampFormat = $format;
  551. return $this;
  552. }
  553. /**
  554. * Get timestamp format used for log entries.
  555. *
  556. * @return string
  557. */
  558. public function getTimestampFormat()
  559. {
  560. return $this->_timestampFormat;
  561. }
  562. }