PHPConsoleHandler.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. <?php
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use Exception;
  12. use Monolog\Formatter\LineFormatter;
  13. use Monolog\Logger;
  14. use PhpConsole\Connector;
  15. use PhpConsole\Handler as VendorPhpConsoleHandler;
  16. use PhpConsole\Helper;
  17. /**
  18. * Monolog handler for Google Chrome extension "PHP Console"
  19. *
  20. * Display PHP error/debug log messages in Google Chrome console and notification popups, executes PHP code remotely
  21. *
  22. * Usage:
  23. * 1. Install Google Chrome extension https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef
  24. * 2. See overview https://github.com/barbushin/php-console#overview
  25. * 3. Install PHP Console library https://github.com/barbushin/php-console#installation
  26. * 4. Example (result will looks like http://i.hizliresim.com/vg3Pz4.png)
  27. *
  28. * $logger = new \Monolog\Logger('all', array(new \Monolog\Handler\PHPConsoleHandler()));
  29. * \Monolog\ErrorHandler::register($logger);
  30. * echo $undefinedVar;
  31. * $logger->addDebug('SELECT * FROM users', array('db', 'time' => 0.012));
  32. * PC::debug($_SERVER); // PHP Console debugger for any type of vars
  33. *
  34. * @author Sergey Barbushin https://www.linkedin.com/in/barbushin
  35. */
  36. class PHPConsoleHandler extends AbstractProcessingHandler
  37. {
  38. private $options = array(
  39. 'enabled' => true, // bool Is PHP Console server enabled
  40. 'classesPartialsTraceIgnore' => array('Monolog\\'), // array Hide calls of classes started with...
  41. 'debugTagsKeysInContext' => array(0, 'tag'), // bool Is PHP Console server enabled
  42. 'useOwnErrorsHandler' => false, // bool Enable errors handling
  43. 'useOwnExceptionsHandler' => false, // bool Enable exceptions handling
  44. 'sourcesBasePath' => null, // string Base path of all project sources to strip in errors source paths
  45. 'registerHelper' => true, // bool Register PhpConsole\Helper that allows short debug calls like PC::debug($var, 'ta.g.s')
  46. 'serverEncoding' => null, // string|null Server internal encoding
  47. 'headersLimit' => null, // int|null Set headers size limit for your web-server
  48. 'password' => null, // string|null Protect PHP Console connection by password
  49. 'enableSslOnlyMode' => false, // bool Force connection by SSL for clients with PHP Console installed
  50. 'ipMasks' => array(), // array Set IP masks of clients that will be allowed to connect to PHP Console: array('192.168.*.*', '127.0.0.1')
  51. 'enableEvalListener' => false, // bool Enable eval request to be handled by eval dispatcher(if enabled, 'password' option is also required)
  52. 'dumperDetectCallbacks' => false, // bool Convert callback items in dumper vars to (callback SomeClass::someMethod) strings
  53. 'dumperLevelLimit' => 5, // int Maximum dumped vars array or object nested dump level
  54. 'dumperItemsCountLimit' => 100, // int Maximum dumped var same level array items or object properties number
  55. 'dumperItemSizeLimit' => 5000, // int Maximum length of any string or dumped array item
  56. 'dumperDumpSizeLimit' => 500000, // int Maximum approximate size of dumped vars result formatted in JSON
  57. 'detectDumpTraceAndSource' => false, // bool Autodetect and append trace data to debug
  58. 'dataStorage' => null, // PhpConsole\Storage|null Fixes problem with custom $_SESSION handler(see http://goo.gl/Ne8juJ)
  59. );
  60. /** @var Connector */
  61. private $connector;
  62. /**
  63. * @param array $options See \Monolog\Handler\PHPConsoleHandler::$options for more details
  64. * @param Connector|null $connector Instance of \PhpConsole\Connector class (optional)
  65. * @param int $level
  66. * @param bool $bubble
  67. * @throws Exception
  68. */
  69. public function __construct(array $options = array(), Connector $connector = null, $level = Logger::DEBUG, $bubble = true)
  70. {
  71. if (!class_exists('PhpConsole\Connector')) {
  72. throw new Exception('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
  73. }
  74. parent::__construct($level, $bubble);
  75. $this->options = $this->initOptions($options);
  76. $this->connector = $this->initConnector($connector);
  77. }
  78. private function initOptions(array $options)
  79. {
  80. $wrongOptions = array_diff(array_keys($options), array_keys($this->options));
  81. if ($wrongOptions) {
  82. throw new Exception('Unknown options: ' . implode(', ', $wrongOptions));
  83. }
  84. return array_replace($this->options, $options);
  85. }
  86. private function initConnector(Connector $connector = null)
  87. {
  88. if (!$connector) {
  89. if ($this->options['dataStorage']) {
  90. Connector::setPostponeStorage($this->options['dataStorage']);
  91. }
  92. $connector = Connector::getInstance();
  93. }
  94. if ($this->options['registerHelper'] && !Helper::isRegistered()) {
  95. Helper::register();
  96. }
  97. if ($this->options['enabled'] && $connector->isActiveClient()) {
  98. if ($this->options['useOwnErrorsHandler'] || $this->options['useOwnExceptionsHandler']) {
  99. $handler = VendorPhpConsoleHandler::getInstance();
  100. $handler->setHandleErrors($this->options['useOwnErrorsHandler']);
  101. $handler->setHandleExceptions($this->options['useOwnExceptionsHandler']);
  102. $handler->start();
  103. }
  104. if ($this->options['sourcesBasePath']) {
  105. $connector->setSourcesBasePath($this->options['sourcesBasePath']);
  106. }
  107. if ($this->options['serverEncoding']) {
  108. $connector->setServerEncoding($this->options['serverEncoding']);
  109. }
  110. if ($this->options['password']) {
  111. $connector->setPassword($this->options['password']);
  112. }
  113. if ($this->options['enableSslOnlyMode']) {
  114. $connector->enableSslOnlyMode();
  115. }
  116. if ($this->options['ipMasks']) {
  117. $connector->setAllowedIpMasks($this->options['ipMasks']);
  118. }
  119. if ($this->options['headersLimit']) {
  120. $connector->setHeadersLimit($this->options['headersLimit']);
  121. }
  122. if ($this->options['detectDumpTraceAndSource']) {
  123. $connector->getDebugDispatcher()->detectTraceAndSource = true;
  124. }
  125. $dumper = $connector->getDumper();
  126. $dumper->levelLimit = $this->options['dumperLevelLimit'];
  127. $dumper->itemsCountLimit = $this->options['dumperItemsCountLimit'];
  128. $dumper->itemSizeLimit = $this->options['dumperItemSizeLimit'];
  129. $dumper->dumpSizeLimit = $this->options['dumperDumpSizeLimit'];
  130. $dumper->detectCallbacks = $this->options['dumperDetectCallbacks'];
  131. if ($this->options['enableEvalListener']) {
  132. $connector->startEvalRequestsListener();
  133. }
  134. }
  135. return $connector;
  136. }
  137. public function getConnector()
  138. {
  139. return $this->connector;
  140. }
  141. public function getOptions()
  142. {
  143. return $this->options;
  144. }
  145. public function handle(array $record)
  146. {
  147. if ($this->options['enabled'] && $this->connector->isActiveClient()) {
  148. return parent::handle($record);
  149. }
  150. return !$this->bubble;
  151. }
  152. /**
  153. * Writes the record down to the log of the implementing handler
  154. *
  155. * @param array $record
  156. * @return void
  157. */
  158. protected function write(array $record)
  159. {
  160. if ($record['level'] < Logger::NOTICE) {
  161. $this->handleDebugRecord($record);
  162. } elseif (isset($record['context']['exception']) && $record['context']['exception'] instanceof Exception) {
  163. $this->handleExceptionRecord($record);
  164. } else {
  165. $this->handleErrorRecord($record);
  166. }
  167. }
  168. private function handleDebugRecord(array $record)
  169. {
  170. $tags = $this->getRecordTags($record);
  171. $message = $record['message'];
  172. if ($record['context']) {
  173. $message .= ' ' . json_encode($this->connector->getDumper()->dump(array_filter($record['context'])));
  174. }
  175. $this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']);
  176. }
  177. private function handleExceptionRecord(array $record)
  178. {
  179. $this->connector->getErrorsDispatcher()->dispatchException($record['context']['exception']);
  180. }
  181. private function handleErrorRecord(array $record)
  182. {
  183. $context = $record['context'];
  184. $this->connector->getErrorsDispatcher()->dispatchError(
  185. isset($context['code']) ? $context['code'] : null,
  186. isset($context['message']) ? $context['message'] : $record['message'],
  187. isset($context['file']) ? $context['file'] : null,
  188. isset($context['line']) ? $context['line'] : null,
  189. $this->options['classesPartialsTraceIgnore']
  190. );
  191. }
  192. private function getRecordTags(array &$record)
  193. {
  194. $tags = null;
  195. if (!empty($record['context'])) {
  196. $context = & $record['context'];
  197. foreach ($this->options['debugTagsKeysInContext'] as $key) {
  198. if (!empty($context[$key])) {
  199. $tags = $context[$key];
  200. if ($key === 0) {
  201. array_shift($context);
  202. } else {
  203. unset($context[$key]);
  204. }
  205. break;
  206. }
  207. }
  208. }
  209. return $tags ?: strtolower($record['level_name']);
  210. }
  211. /**
  212. * {@inheritDoc}
  213. */
  214. protected function getDefaultFormatter()
  215. {
  216. return new LineFormatter('%message%');
  217. }
  218. }