Log.php 20 KB

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