Log.php 20 KB

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