PHPConsoleHandler.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php declare(strict_types=1);
  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 Monolog\Formatter\LineFormatter;
  12. use Monolog\Formatter\FormatterInterface;
  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->debug('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 = [
  39. 'enabled' => true, // bool Is PHP Console server enabled
  40. 'classesPartialsTraceIgnore' => ['Monolog\\'], // array Hide calls of classes started with...
  41. 'debugTagsKeysInContext' => [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 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|string $level
  66. * @param bool $bubble
  67. * @throws \RuntimeException
  68. */
  69. public function __construct(array $options = [], ?Connector $connector = null, $level = Logger::DEBUG, bool $bubble = true)
  70. {
  71. if (!class_exists('PhpConsole\Connector')) {
  72. throw new \RuntimeException('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 \RuntimeException('Unknown options: ' . implode(', ', $wrongOptions));
  83. }
  84. return array_replace($this->options, $options);
  85. }
  86. /**
  87. * @suppress PhanTypeMismatchArgument
  88. */
  89. private function initConnector(Connector $connector = null): Connector
  90. {
  91. if (!$connector) {
  92. if ($this->options['dataStorage']) {
  93. Connector::setPostponeStorage($this->options['dataStorage']);
  94. }
  95. $connector = Connector::getInstance();
  96. }
  97. if ($this->options['registerHelper'] && !Helper::isRegistered()) {
  98. Helper::register();
  99. }
  100. if ($this->options['enabled'] && $connector->isActiveClient()) {
  101. if ($this->options['useOwnErrorsHandler'] || $this->options['useOwnExceptionsHandler']) {
  102. $handler = VendorPhpConsoleHandler::getInstance();
  103. $handler->setHandleErrors($this->options['useOwnErrorsHandler']);
  104. $handler->setHandleExceptions($this->options['useOwnExceptionsHandler']);
  105. $handler->start();
  106. }
  107. if ($this->options['sourcesBasePath']) {
  108. $connector->setSourcesBasePath($this->options['sourcesBasePath']);
  109. }
  110. if ($this->options['serverEncoding']) {
  111. $connector->setServerEncoding($this->options['serverEncoding']);
  112. }
  113. if ($this->options['password']) {
  114. $connector->setPassword($this->options['password']);
  115. }
  116. if ($this->options['enableSslOnlyMode']) {
  117. $connector->enableSslOnlyMode();
  118. }
  119. if ($this->options['ipMasks']) {
  120. $connector->setAllowedIpMasks($this->options['ipMasks']);
  121. }
  122. if ($this->options['headersLimit']) {
  123. $connector->setHeadersLimit($this->options['headersLimit']);
  124. }
  125. if ($this->options['detectDumpTraceAndSource']) {
  126. $connector->getDebugDispatcher()->detectTraceAndSource = true;
  127. }
  128. $dumper = $connector->getDumper();
  129. $dumper->levelLimit = $this->options['dumperLevelLimit'];
  130. $dumper->itemsCountLimit = $this->options['dumperItemsCountLimit'];
  131. $dumper->itemSizeLimit = $this->options['dumperItemSizeLimit'];
  132. $dumper->dumpSizeLimit = $this->options['dumperDumpSizeLimit'];
  133. $dumper->detectCallbacks = $this->options['dumperDetectCallbacks'];
  134. if ($this->options['enableEvalListener']) {
  135. $connector->startEvalRequestsListener();
  136. }
  137. }
  138. return $connector;
  139. }
  140. public function getConnector(): Connector
  141. {
  142. return $this->connector;
  143. }
  144. public function getOptions(): array
  145. {
  146. return $this->options;
  147. }
  148. public function handle(array $record): bool
  149. {
  150. if ($this->options['enabled'] && $this->connector->isActiveClient()) {
  151. return parent::handle($record);
  152. }
  153. return !$this->bubble;
  154. }
  155. /**
  156. * Writes the record down to the log of the implementing handler
  157. *
  158. * @param array $record
  159. * @return void
  160. */
  161. protected function write(array $record): void
  162. {
  163. if ($record['level'] < Logger::NOTICE) {
  164. $this->handleDebugRecord($record);
  165. } elseif (isset($record['context']['exception']) && $record['context']['exception'] instanceof \Throwable) {
  166. $this->handleExceptionRecord($record);
  167. } else {
  168. $this->handleErrorRecord($record);
  169. }
  170. }
  171. private function handleDebugRecord(array $record): void
  172. {
  173. $tags = $this->getRecordTags($record);
  174. $message = $record['message'];
  175. if ($record['context']) {
  176. $message .= ' ' . json_encode($this->connector->getDumper()->dump(array_filter($record['context'])));
  177. }
  178. $this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']);
  179. }
  180. private function handleExceptionRecord(array $record): void
  181. {
  182. $this->connector->getErrorsDispatcher()->dispatchException($record['context']['exception']);
  183. }
  184. private function handleErrorRecord(array $record): void
  185. {
  186. $context = $record['context'];
  187. $this->connector->getErrorsDispatcher()->dispatchError(
  188. $context['code'] ?? null,
  189. $context['message'] ?? $record['message'],
  190. $context['file'] ?? null,
  191. $context['line'] ?? null,
  192. $this->options['classesPartialsTraceIgnore']
  193. );
  194. }
  195. private function getRecordTags(array &$record)
  196. {
  197. $tags = null;
  198. if (!empty($record['context'])) {
  199. $context = & $record['context'];
  200. foreach ($this->options['debugTagsKeysInContext'] as $key) {
  201. if (!empty($context[$key])) {
  202. $tags = $context[$key];
  203. if ($key === 0) {
  204. array_shift($context);
  205. } else {
  206. unset($context[$key]);
  207. }
  208. break;
  209. }
  210. }
  211. }
  212. return $tags ?: strtolower($record['level_name']);
  213. }
  214. /**
  215. * {@inheritDoc}
  216. */
  217. protected function getDefaultFormatter(): FormatterInterface
  218. {
  219. return new LineFormatter('%message%');
  220. }
  221. }