Log.php 17 KB

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