Log.php 17 KB

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