Console.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. namespace think\debug;
  12. use think\Cache;
  13. use think\Config;
  14. use think\Db;
  15. use think\Debug;
  16. use think\Request;
  17. use think\Response;
  18. /**
  19. * 浏览器调试输出
  20. */
  21. class Console
  22. {
  23. protected $config = [
  24. 'trace_tabs' => ['base' => '基本', 'file' => '文件', 'info' => '流程', 'notice|error' => '错误', 'sql' => 'SQL', 'debug|log' => '调试'],
  25. ];
  26. // 实例化并传入参数
  27. public function __construct($config = [])
  28. {
  29. if (is_array($config)) {
  30. $this->config = array_merge($this->config, $config);
  31. }
  32. }
  33. /**
  34. * 调试输出接口
  35. * @access public
  36. * @param Response $response Response对象
  37. * @param array $log 日志信息
  38. * @return bool
  39. */
  40. public function output(Response $response, array $log = [])
  41. {
  42. $request = Request::instance();
  43. $contentType = $response->getHeader('Content-Type');
  44. $accept = $request->header('accept');
  45. if (strpos($accept, 'application/json') === 0 || $request->isAjax()) {
  46. return false;
  47. } elseif (!empty($contentType) && strpos($contentType, 'html') === false) {
  48. return false;
  49. }
  50. // 获取基本信息
  51. $runtime = number_format(microtime(true) - THINK_START_TIME, 10);
  52. $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
  53. $mem = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);
  54. if (isset($_SERVER['HTTP_HOST'])) {
  55. $uri = $_SERVER['SERVER_PROTOCOL'] . ' ' . $_SERVER['REQUEST_METHOD'] . ' : ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  56. } else {
  57. $uri = 'cmd:' . implode(' ', $_SERVER['argv']);
  58. }
  59. // 页面Trace信息
  60. $base = [
  61. '请求信息' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']) . ' ' . $uri,
  62. '运行时间' => number_format($runtime, 6) . 's [ 吞吐率:' . $reqs . 'req/s ] 内存消耗:' . $mem . 'kb 文件加载:' . count(get_included_files()),
  63. '查询信息' => Db::$queryTimes . ' queries ' . Db::$executeTimes . ' writes ',
  64. '缓存信息' => Cache::$readTimes . ' reads,' . Cache::$writeTimes . ' writes',
  65. '配置加载' => count(Config::get()),
  66. ];
  67. if (session_id()) {
  68. $base['会话信息'] = 'SESSION_ID=' . session_id();
  69. }
  70. $info = Debug::getFile(true);
  71. // 页面Trace信息
  72. $trace = [];
  73. foreach ($this->config['trace_tabs'] as $name => $title) {
  74. $name = strtolower($name);
  75. switch ($name) {
  76. case 'base': // 基本信息
  77. $trace[$title] = $base;
  78. break;
  79. case 'file': // 文件信息
  80. $trace[$title] = $info;
  81. break;
  82. default: // 调试信息
  83. if (strpos($name, '|')) {
  84. // 多组信息
  85. $names = explode('|', $name);
  86. $result = [];
  87. foreach ($names as $name) {
  88. $result = array_merge($result, isset($log[$name]) ? $log[$name] : []);
  89. }
  90. $trace[$title] = $result;
  91. } else {
  92. $trace[$title] = isset($log[$name]) ? $log[$name] : '';
  93. }
  94. }
  95. }
  96. //输出到控制台
  97. $lines = '';
  98. foreach ($trace as $type => $msg) {
  99. $lines .= $this->console($type, $msg);
  100. }
  101. $js = <<<JS
  102. <script type='text/javascript'>
  103. {$lines}
  104. </script>
  105. JS;
  106. return $js;
  107. }
  108. protected function console($type, $msg)
  109. {
  110. $type = strtolower($type);
  111. $trace_tabs = array_values($this->config['trace_tabs']);
  112. $line[] = ($type == $trace_tabs[0] || '调试' == $type || '错误' == $type)
  113. ? "console.group('{$type}');"
  114. : "console.groupCollapsed('{$type}');";
  115. foreach ((array) $msg as $key => $m) {
  116. switch ($type) {
  117. case '调试':
  118. $var_type = gettype($m);
  119. if (in_array($var_type, ['array', 'string'])) {
  120. $line[] = "console.log(" . json_encode($m) . ");";
  121. } else {
  122. $line[] = "console.log(" . json_encode(var_export($m, 1)) . ");";
  123. }
  124. break;
  125. case '错误':
  126. $msg = str_replace("\n", '\n', json_encode($m));
  127. $style = 'color:#F4006B;font-size:14px;';
  128. $line[] = "console.error(\"%c{$msg}\", \"{$style}\");";
  129. break;
  130. case 'sql':
  131. $msg = str_replace("\n", '\n', $m);
  132. $style = "color:#009bb4;";
  133. $line[] = "console.log(\"%c{$msg}\", \"{$style}\");";
  134. break;
  135. default:
  136. $m = is_string($key) ? $key . ' ' . $m : $key + 1 . ' ' . $m;
  137. $msg = json_encode($m);
  138. $line[] = "console.log({$msg});";
  139. break;
  140. }
  141. }
  142. $line[] = "console.groupEnd();";
  143. return implode(PHP_EOL, $line);
  144. }
  145. }