Console.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. if ($request->isJson() || $request->isAjax()) {
  40. return false;
  41. } elseif (!empty($contentType) && strpos($contentType, 'html') === false) {
  42. return false;
  43. } elseif ($response->getCode() == 204) {
  44. return false;
  45. }
  46. // 获取基本信息
  47. $runtime = number_format(microtime(true) - $app->getBeginTime(), 10, '.', '');
  48. $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
  49. $mem = number_format((memory_get_usage() - $app->getBeginMem()) / 1024, 2);
  50. if ($request->host()) {
  51. $uri = $request->protocol() . ' ' . $request->method() . ' : ' . $request->url(true);
  52. } else {
  53. $uri = 'cmd:' . implode(' ', $_SERVER['argv']);
  54. }
  55. // 页面Trace信息
  56. $base = [
  57. '请求信息' => date('Y-m-d H:i:s', $request->time() ?: time()) . ' ' . $uri,
  58. '运行时间' => number_format((float) $runtime, 6) . 's [ 吞吐率:' . $reqs . 'req/s ] 内存消耗:' . $mem . 'kb 文件加载:' . count(get_included_files()),
  59. '查询信息' => $app->db->getQueryTimes() . ' queries',
  60. '缓存信息' => $app->cache->getReadTimes() . ' reads,' . $app->cache->getWriteTimes() . ' writes',
  61. ];
  62. if (isset($app->session)) {
  63. $base['会话信息'] = 'SESSION_ID=' . $app->session->getId();
  64. }
  65. $info = $this->getFileInfo();
  66. // 页面Trace信息
  67. $trace = [];
  68. foreach ($this->config['tabs'] as $name => $title) {
  69. $name = strtolower($name);
  70. switch ($name) {
  71. case 'base': // 基本信息
  72. $trace[$title] = $base;
  73. break;
  74. case 'file': // 文件信息
  75. $trace[$title] = $info;
  76. break;
  77. default: // 调试信息
  78. if (strpos($name, '|')) {
  79. // 多组信息
  80. $names = explode('|', $name);
  81. $result = [];
  82. foreach ($names as $item) {
  83. $result = array_merge($result, $log[$item] ?? []);
  84. }
  85. $trace[$title] = $result;
  86. } else {
  87. $trace[$title] = $log[$name] ?? '';
  88. }
  89. }
  90. }
  91. //输出到控制台
  92. $lines = '';
  93. foreach ($trace as $type => $msg) {
  94. $lines .= $this->console($type, empty($msg) ? [] : $msg);
  95. }
  96. $js = <<<JS
  97. <script type='text/javascript'>
  98. {$lines}
  99. </script>
  100. JS;
  101. return $js;
  102. }
  103. protected function console(string $type, $msg)
  104. {
  105. $type = strtolower($type);
  106. $trace_tabs = array_values($this->config['tabs']);
  107. $line = [];
  108. $line[] = ($type == $trace_tabs[0] || '调试' == $type || '错误' == $type)
  109. ? "console.group('{$type}');"
  110. : "console.groupCollapsed('{$type}');";
  111. foreach ((array) $msg as $key => $m) {
  112. switch ($type) {
  113. case '调试':
  114. $var_type = gettype($m);
  115. if (in_array($var_type, ['array', 'string'])) {
  116. $line[] = "console.log(" . json_encode($m) . ");";
  117. } else {
  118. $line[] = "console.log(" . json_encode(var_export($m, true)) . ");";
  119. }
  120. break;
  121. case '错误':
  122. $msg = str_replace("\n", '\n', addslashes(is_scalar($m) ? $m : json_encode($m)));
  123. $style = 'color:#F4006B;font-size:14px;';
  124. $line[] = "console.error(\"%c{$msg}\", \"{$style}\");";
  125. break;
  126. case 'sql':
  127. $msg = str_replace("\n", '\n', addslashes($m));
  128. $style = "color:#009bb4;";
  129. $line[] = "console.log(\"%c{$msg}\", \"{$style}\");";
  130. break;
  131. default:
  132. $m = is_string($key) ? $key . ' ' . $m : $key + 1 . ' ' . $m;
  133. $msg = json_encode($m);
  134. $line[] = "console.log({$msg});";
  135. break;
  136. }
  137. }
  138. $line[] = "console.groupEnd();";
  139. return implode(PHP_EOL, $line);
  140. }
  141. /**
  142. * 获取文件加载信息
  143. * @access protected
  144. * @return integer|array
  145. */
  146. protected function getFileInfo()
  147. {
  148. $files = get_included_files();
  149. $info = [];
  150. foreach ($files as $key => $file) {
  151. $info[] = $file . ' ( ' . number_format(filesize($file) / 1024, 2) . ' KB )';
  152. }
  153. return $info;
  154. }
  155. }