Log.php 17 KB

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