PHPConsoleHandler.php 12 KB

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