Log.php 20 KB

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