PageRenderTime 36ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/Log.php

https://bitbucket.org/jfrubiom/zendframework-1.x
PHP | 624 lines | 314 code | 69 blank | 241 comment | 50 complexity | 1e24fae505f151ea4150b413d671b152 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 24593 2012-01-05 20:35:02Z matthew $
  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 24593 2012-01-05 20:35:02Z matthew $
  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. $fullClassName = $namespace . '_' . $className;
  262. return $fullClassName;
  263. }
  264. /**
  265. * Packs message and priority into Event array
  266. *
  267. * @param string $message Message to log
  268. * @param integer $priority Priority of message
  269. * @return array Event array
  270. */
  271. protected function _packEvent($message, $priority)
  272. {
  273. return array_merge(array(
  274. 'timestamp' => date($this->_timestampFormat),
  275. 'message' => $message,
  276. 'priority' => $priority,
  277. 'priorityName' => $this->_priorities[$priority]
  278. ),
  279. $this->_extras
  280. );
  281. }
  282. /**
  283. * Class destructor. Shutdown log writers
  284. *
  285. * @return void
  286. */
  287. public function __destruct()
  288. {
  289. foreach($this->_writers as $writer) {
  290. $writer->shutdown();
  291. }
  292. }
  293. /**
  294. * Undefined method handler allows a shortcut:
  295. * $log->priorityName('message')
  296. * instead of
  297. * $log->log('message', Zend_Log::PRIORITY_NAME)
  298. *
  299. * @param string $method priority name
  300. * @param string $params message to log
  301. * @return void
  302. * @throws Zend_Log_Exception
  303. */
  304. public function __call($method, $params)
  305. {
  306. $priority = strtoupper($method);
  307. if (($priority = array_search($priority, $this->_priorities)) !== false) {
  308. switch (count($params)) {
  309. case 0:
  310. /** @see Zend_Log_Exception */
  311. require_once 'Zend/Log/Exception.php';
  312. throw new Zend_Log_Exception('Missing log message');
  313. case 1:
  314. $message = array_shift($params);
  315. $extras = null;
  316. break;
  317. default:
  318. $message = array_shift($params);
  319. $extras = array_shift($params);
  320. break;
  321. }
  322. $this->log($message, $priority, $extras);
  323. } else {
  324. /** @see Zend_Log_Exception */
  325. require_once 'Zend/Log/Exception.php';
  326. throw new Zend_Log_Exception('Bad log priority');
  327. }
  328. }
  329. /**
  330. * Log a message at a priority
  331. *
  332. * @param string $message Message to log
  333. * @param integer $priority Priority of message
  334. * @param mixed $extras Extra information to log in event
  335. * @return void
  336. * @throws Zend_Log_Exception
  337. */
  338. public function log($message, $priority, $extras = null)
  339. {
  340. // sanity checks
  341. if (empty($this->_writers)) {
  342. /** @see Zend_Log_Exception */
  343. require_once 'Zend/Log/Exception.php';
  344. throw new Zend_Log_Exception('No writers were added');
  345. }
  346. if (! isset($this->_priorities[$priority])) {
  347. /** @see Zend_Log_Exception */
  348. require_once 'Zend/Log/Exception.php';
  349. throw new Zend_Log_Exception('Bad log priority');
  350. }
  351. // pack into event required by filters and writers
  352. $event = $this->_packEvent($message, $priority);
  353. // Check to see if any extra information was passed
  354. if (!empty($extras)) {
  355. $info = array();
  356. if (is_array($extras)) {
  357. foreach ($extras as $key => $value) {
  358. if (is_string($key)) {
  359. $event[$key] = $value;
  360. } else {
  361. $info[] = $value;
  362. }
  363. }
  364. } else {
  365. $info = $extras;
  366. }
  367. if (!empty($info)) {
  368. $event['info'] = $info;
  369. }
  370. }
  371. // abort if rejected by the global filters
  372. foreach ($this->_filters as $filter) {
  373. if (! $filter->accept($event)) {
  374. return;
  375. }
  376. }
  377. // send to each writer
  378. foreach ($this->_writers as $writer) {
  379. $writer->write($event);
  380. }
  381. }
  382. /**
  383. * Add a custom priority
  384. *
  385. * @param string $name Name of priority
  386. * @param integer $priority Numeric priority
  387. * @throws Zend_Log_Exception
  388. */
  389. public function addPriority($name, $priority)
  390. {
  391. // Priority names must be uppercase for predictability.
  392. $name = strtoupper($name);
  393. if (isset($this->_priorities[$priority])
  394. || false !== array_search($name, $this->_priorities)) {
  395. /** @see Zend_Log_Exception */
  396. require_once 'Zend/Log/Exception.php';
  397. throw new Zend_Log_Exception('Existing priorities cannot be overwritten');
  398. }
  399. $this->_priorities[$priority] = $name;
  400. return $this;
  401. }
  402. /**
  403. * Add a filter that will be applied before all log writers.
  404. * Before a message will be received by any of the writers, it
  405. * must be accepted by all filters added with this method.
  406. *
  407. * @param int|Zend_Config|array|Zend_Log_Filter_Interface $filter
  408. * @return Zend_Log
  409. * @throws Zend_Log_Exception
  410. */
  411. public function addFilter($filter)
  412. {
  413. if (is_int($filter)) {
  414. /** @see Zend_Log_Filter_Priority */
  415. require_once 'Zend/Log/Filter/Priority.php';
  416. $filter = new Zend_Log_Filter_Priority($filter);
  417. } elseif ($filter instanceof Zend_Config || is_array($filter)) {
  418. $filter = $this->_constructFilterFromConfig($filter);
  419. } elseif(! $filter instanceof Zend_Log_Filter_Interface) {
  420. /** @see Zend_Log_Exception */
  421. require_once 'Zend/Log/Exception.php';
  422. throw new Zend_Log_Exception('Invalid filter provided');
  423. }
  424. $this->_filters[] = $filter;
  425. return $this;
  426. }
  427. /**
  428. * Add a writer. A writer is responsible for taking a log
  429. * message and writing it out to storage.
  430. *
  431. * @param mixed $writer Zend_Log_Writer_Abstract or Config array
  432. * @return Zend_Log
  433. */
  434. public function addWriter($writer)
  435. {
  436. if (is_array($writer) || $writer instanceof Zend_Config) {
  437. $writer = $this->_constructWriterFromConfig($writer);
  438. }
  439. if (!$writer instanceof Zend_Log_Writer_Abstract) {
  440. /** @see Zend_Log_Exception */
  441. require_once 'Zend/Log/Exception.php';
  442. throw new Zend_Log_Exception(
  443. 'Writer must be an instance of Zend_Log_Writer_Abstract'
  444. . ' or you should pass a configuration array'
  445. );
  446. }
  447. $this->_writers[] = $writer;
  448. return $this;
  449. }
  450. /**
  451. * Set an extra item to pass to the log writers.
  452. *
  453. * @param string $name Name of the field
  454. * @param string $value Value of the field
  455. * @return Zend_Log
  456. */
  457. public function setEventItem($name, $value)
  458. {
  459. $this->_extras = array_merge($this->_extras, array($name => $value));
  460. return $this;
  461. }
  462. /**
  463. * Register Logging system as an error handler to log php errors
  464. * Note: it still calls the original error handler if set_error_handler is able to return it.
  465. *
  466. * Errors will be mapped as:
  467. * E_NOTICE, E_USER_NOTICE => NOTICE
  468. * E_WARNING, E_CORE_WARNING, E_USER_WARNING => WARN
  469. * E_ERROR, E_USER_ERROR, E_CORE_ERROR, E_RECOVERABLE_ERROR => ERR
  470. * E_DEPRECATED, E_STRICT, E_USER_DEPRECATED => DEBUG
  471. * (unknown/other) => INFO
  472. *
  473. * @link http://www.php.net/manual/en/function.set-error-handler.php Custom error handler
  474. *
  475. * @return Zend_Log
  476. */
  477. public function registerErrorHandler()
  478. {
  479. // Only register once. Avoids loop issues if it gets registered twice.
  480. if ($this->_registeredErrorHandler) {
  481. return $this;
  482. }
  483. $this->_origErrorHandler = set_error_handler(array($this, 'errorHandler'));
  484. // Contruct a default map of phpErrors to Zend_Log priorities.
  485. // Some of the errors are uncatchable, but are included for completeness
  486. $this->_errorHandlerMap = array(
  487. E_NOTICE => Zend_Log::NOTICE,
  488. E_USER_NOTICE => Zend_Log::NOTICE,
  489. E_WARNING => Zend_Log::WARN,
  490. E_CORE_WARNING => Zend_Log::WARN,
  491. E_USER_WARNING => Zend_Log::WARN,
  492. E_ERROR => Zend_Log::ERR,
  493. E_USER_ERROR => Zend_Log::ERR,
  494. E_CORE_ERROR => Zend_Log::ERR,
  495. E_RECOVERABLE_ERROR => Zend_Log::ERR,
  496. E_STRICT => Zend_Log::DEBUG,
  497. );
  498. // PHP 5.3.0+
  499. if (defined('E_DEPRECATED')) {
  500. $this->_errorHandlerMap['E_DEPRECATED'] = Zend_Log::DEBUG;
  501. }
  502. if (defined('E_USER_DEPRECATED')) {
  503. $this->_errorHandlerMap['E_USER_DEPRECATED'] = Zend_Log::DEBUG;
  504. }
  505. $this->_registeredErrorHandler = true;
  506. return $this;
  507. }
  508. /**
  509. * Error Handler will convert error into log message, and then call the original error handler
  510. *
  511. * @link http://www.php.net/manual/en/function.set-error-handler.php Custom error handler
  512. * @param int $errno
  513. * @param string $errstr
  514. * @param string $errfile
  515. * @param int $errline
  516. * @param array $errcontext
  517. * @return boolean
  518. */
  519. public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
  520. {
  521. $errorLevel = error_reporting();
  522. if ($errorLevel && $errno) {
  523. if (isset($this->_errorHandlerMap[$errno])) {
  524. $priority = $this->_errorHandlerMap[$errno];
  525. } else {
  526. $priority = Zend_Log::INFO;
  527. }
  528. $this->log($errstr, $priority, array('errno'=>$errno, 'file'=>$errfile, 'line'=>$errline, 'context'=>$errcontext));
  529. }
  530. if ($this->_origErrorHandler !== null) {
  531. return call_user_func($this->_origErrorHandler, $errno, $errstr, $errfile, $errline, $errcontext);
  532. }
  533. return false;
  534. }
  535. /**
  536. * Set timestamp format for log entries.
  537. *
  538. * @param string $format
  539. * @return Zend_Log
  540. */
  541. public function setTimestampFormat($format)
  542. {
  543. $this->_timestampFormat = $format;
  544. return $this;
  545. }
  546. /**
  547. * Get timestamp format used for log entries.
  548. *
  549. * @return string
  550. */
  551. public function getTimestampFormat()
  552. {
  553. return $this->_timestampFormat;
  554. }
  555. }