Console.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yangweijie <yangweijiester@gmail.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace think\trace;
  13. use think\App;
  14. use think\Response;
  15. /**
  16. * 浏览器调试输出
  17. */
  18. class Console
  19. {
  20. protected $config = [
  21. 'tabs' => ['base' => '基本', 'file' => '文件', 'info' => '流程', 'notice|error' => '错误', 'sql' => 'SQL', 'debug|log' => '调试'],
  22. ];
  23. // 实例化并传入参数
  24. public function __construct(array $config = [])
  25. {
  26. $this->config = array_merge($this->config, $config);
  27. }
  28. /**
  29. * 调试输出接口
  30. * @access public
  31. * @param Response $response Response对象
  32. * @param array $log 日志信息
  33. * @return string|bool
  34. */
  35. public function output(App $app, Response $response, array $log = [])
  36. {
  37. $request = $app->request;
  38. $contentType = $response->getHeader('Content-Type');
  39. $accept = $request->header('accept', '');
  40. if (strpos($accept, 'application/json') === 0 || $request->isAjax()) {
  41. return false;
  42. } elseif (!empty($contentType) && strpos($contentType, 'html') === false) {
  43. return false;
  44. }
  45. // 获取基本信息
  46. $runtime = number_format(microtime(true) - $app->getBeginTime(), 10, '.', '');
  47. $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
  48. $mem = number_format((memory_get_usage() - $app->getBeginMem()) / 1024, 2);
  49. if ($request->host()) {
  50. $uri = $request->protocol() . ' ' . $request->method() . ' : ' . $request->url(true);
  51. } else {
  52. $uri = 'cmd:' . implode(' ', $_SERVER['argv']);
  53. }
  54. // 页面Trace信息
  55. $base = [
  56. '请求信息' => date('Y-m-d H:i:s', $request->time() ?: time()) . ' ' . $uri,
  57. '运行时间' => number_format((float) $runtime, 6) . 's [ 吞吐率:' . $reqs . 'req/s ] 内存消耗:' . $mem . 'kb 文件加载:' . count(get_included_files()),
  58. '查询信息' => $app->db->getQueryTimes() . ' queries',
  59. '缓存信息' => $app->cache->getReadTimes() . ' reads,' . $app->cache->getWriteTimes() . ' writes',
  60. ];
  61. if (isset($app->session)) {
  62. $base['会话信息'] = 'SESSION_ID=' . $app->session->getId();
  63. }
  64. $info = $this->getFileInfo();
  65. // 页面Trace信息
  66. $trace = [];
  67. foreach ($this->config['tabs'] as $name => $title) {
  68. $name = strtolower($name);
  69. switch ($name) {
  70. case 'base': // 基本信息
  71. $trace[$title] = $base;
  72. break;
  73. case 'file': // 文件信息
  74. $trace[$title] = $info;
  75. break;
  76. default: // 调试信息
  77. if (strpos($name, '|')) {
  78. // 多组信息
  79. $names = explode('|', $name);
  80. $result = [];
  81. foreach ($names as $item) {
  82. $result = array_merge($result, $log[$item] ?? []);
  83. }
  84. $trace[$title] = $result;
  85. } else {
  86. $trace[$title] = $log[$name] ?? '';
  87. }
  88. }
  89. }
  90. //输出到控制台
  91. $lines = '';
  92. foreach ($trace as $type => $msg) {
  93. $lines .= $this->console($type, empty($msg) ? [] : $msg);
  94. }
  95. $js = <<<JS
  96. <script type='text/javascript'>
  97. {$lines}
  98. </script>
  99. JS;
  100. return $js;
  101. }
  102. protected function console(string $type, $msg)
  103. {
  104. $type = strtolower($type);
  105. $trace_tabs = array_values($this->config['tabs']);
  106. $line = [];
  107. $line[] = ($type == $trace_tabs[0] || '调试' == $type || '错误' == $type)
  108. ? "console.group('{$type}');"
  109. : "console.groupCollapsed('{$type}');";
  110. foreach ((array) $msg as $key => $m) {
  111. switch ($type) {
  112. case '调试':
  113. $var_type = gettype($m);
  114. if (in_array($var_type, ['array', 'string'])) {
  115. $line[] = "console.log(" . json_encode($m) . ");";
  116. } else {
  117. $line[] = "console.log(" . json_encode(var_export($m, true)) . ");";
  118. }
  119. break;
  120. case '错误':
  121. $msg = str_replace("\n", '\n', addslashes(is_scalar($m) ? $m : json_encode($m)));
  122. $style = 'color:#F4006B;font-size:14px;';
  123. $line[] = "console.error(\"%c{$msg}\", \"{$style}\");";
  124. break;
  125. case 'sql':
  126. $msg = str_replace("\n", '\n', addslashes($m));
  127. $style = "color:#009bb4;";
  128. $line[] = "console.log(\"%c{$msg}\", \"{$style}\");";
  129. break;
  130. default:
  131. $m = is_string($key) ? $key . ' ' . $m : $key + 1 . ' ' . $m;
  132. $msg = json_encode($m);
  133. $line[] = "console.log({$msg});";
  134. break;
  135. }
  136. }
  137. $line[] = "console.groupEnd();";
  138. return implode(PHP_EOL, $line);
  139. }
  140. /**
  141. * 获取文件加载信息
  142. * @access protected
  143. * @return integer|array
  144. */
  145. protected function getFileInfo()
  146. {
  147. $files = get_included_files();
  148. $info = [];
  149. foreach ($files as $key => $file) {
  150. $info[] = $file . ' ( ' . number_format(filesize($file) / 1024, 2) . ' KB )';
  151. }
  152. return $info;
  153. }
  154. }