PageRenderTime 61ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Zend/Log.php

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