Log.php 18 KB

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