You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

251 lines
8.0 KiB

  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: luofei614 <weibo.com/luofei614>
  10. // +----------------------------------------------------------------------
  11. namespace think\log\driver;
  12. use think\App;
  13. /**
  14. * github: https://github.com/luofei614/SocketLog
  15. * @author luofei614<weibo.com/luofei614>
  16. */
  17. class Socket
  18. {
  19. public $port = 1116; //SocketLog 服务的http的端口号
  20. protected $config = [
  21. // socket服务器地址
  22. 'host' => 'localhost',
  23. // 是否显示加载的文件列表
  24. 'show_included_files' => false,
  25. // 日志强制记录到配置的client_id
  26. 'force_client_ids' => [],
  27. // 限制允许读取日志的client_id
  28. 'allow_client_ids' => [],
  29. ];
  30. protected $css = [
  31. 'sql' => 'color:#009bb4;',
  32. 'sql_warn' => 'color:#009bb4;font-size:14px;',
  33. 'error' => 'color:#f4006b;font-size:14px;',
  34. 'page' => 'color:#40e2ff;background:#171717;',
  35. 'big' => 'font-size:20px;color:red;',
  36. ];
  37. protected $allowForceClientIds = []; //配置强制推送且被授权的client_id
  38. /**
  39. * 构造函数
  40. * @param array $config 缓存参数
  41. * @access public
  42. */
  43. public function __construct(array $config = [])
  44. {
  45. if (!empty($config)) {
  46. $this->config = array_merge($this->config, $config);
  47. }
  48. }
  49. /**
  50. * 调试输出接口
  51. * @access public
  52. * @param array $log 日志信息
  53. * @return bool
  54. */
  55. public function save(array $log = [], $append = false)
  56. {
  57. if (!$this->check()) {
  58. return false;
  59. }
  60. $trace = [];
  61. if (App::$debug) {
  62. $runtime = round(microtime(true) - THINK_START_TIME, 10);
  63. $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
  64. $time_str = ' [运行时间:' . number_format($runtime, 6) . 's][吞吐率:' . $reqs . 'req/s]';
  65. $memory_use = number_format((memory_get_usage() - THINK_START_MEM) / 1024, 2);
  66. $memory_str = ' [内存消耗:' . $memory_use . 'kb]';
  67. $file_load = ' [文件加载:' . count(get_included_files()) . ']';
  68. if (isset($_SERVER['HTTP_HOST'])) {
  69. $current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  70. } else {
  71. $current_uri = 'cmd:' . implode(' ', $_SERVER['argv']);
  72. }
  73. // 基本信息
  74. $trace[] = [
  75. 'type' => 'group',
  76. 'msg' => $current_uri . $time_str . $memory_str . $file_load,
  77. 'css' => $this->css['page'],
  78. ];
  79. }
  80. foreach ($log as $type => $val) {
  81. $trace[] = [
  82. 'type' => 'groupCollapsed',
  83. 'msg' => '[ ' . $type . ' ]',
  84. 'css' => isset($this->css[$type]) ? $this->css[$type] : '',
  85. ];
  86. foreach ($val as $msg) {
  87. if (!is_string($msg)) {
  88. $msg = var_export($msg, true);
  89. }
  90. $trace[] = [
  91. 'type' => 'log',
  92. 'msg' => $msg,
  93. 'css' => '',
  94. ];
  95. }
  96. $trace[] = [
  97. 'type' => 'groupEnd',
  98. 'msg' => '',
  99. 'css' => '',
  100. ];
  101. }
  102. if ($this->config['show_included_files']) {
  103. $trace[] = [
  104. 'type' => 'groupCollapsed',
  105. 'msg' => '[ file ]',
  106. 'css' => '',
  107. ];
  108. $trace[] = [
  109. 'type' => 'log',
  110. 'msg' => implode("\n", get_included_files()),
  111. 'css' => '',
  112. ];
  113. $trace[] = [
  114. 'type' => 'groupEnd',
  115. 'msg' => '',
  116. 'css' => '',
  117. ];
  118. }
  119. $trace[] = [
  120. 'type' => 'groupEnd',
  121. 'msg' => '',
  122. 'css' => '',
  123. ];
  124. $tabid = $this->getClientArg('tabid');
  125. if (!$client_id = $this->getClientArg('client_id')) {
  126. $client_id = '';
  127. }
  128. if (!empty($this->allowForceClientIds)) {
  129. //强制推送到多个client_id
  130. foreach ($this->allowForceClientIds as $force_client_id) {
  131. $client_id = $force_client_id;
  132. $this->sendToClient($tabid, $client_id, $trace, $force_client_id);
  133. }
  134. } else {
  135. $this->sendToClient($tabid, $client_id, $trace, '');
  136. }
  137. return true;
  138. }
  139. /**
  140. * 发送给指定客户端
  141. * @author Zjmainstay
  142. * @param $tabid
  143. * @param $client_id
  144. * @param $logs
  145. * @param $force_client_id
  146. */
  147. protected function sendToClient($tabid, $client_id, $logs, $force_client_id)
  148. {
  149. $logs = [
  150. 'tabid' => $tabid,
  151. 'client_id' => $client_id,
  152. 'logs' => $logs,
  153. 'force_client_id' => $force_client_id,
  154. ];
  155. $msg = @json_encode($logs);
  156. $address = '/' . $client_id; //将client_id作为地址, server端通过地址判断将日志发布给谁
  157. $this->send($this->config['host'], $msg, $address);
  158. }
  159. protected function check()
  160. {
  161. $tabid = $this->getClientArg('tabid');
  162. //是否记录日志的检查
  163. if (!$tabid && !$this->config['force_client_ids']) {
  164. return false;
  165. }
  166. //用户认证
  167. $allow_client_ids = $this->config['allow_client_ids'];
  168. if (!empty($allow_client_ids)) {
  169. //通过数组交集得出授权强制推送的client_id
  170. $this->allowForceClientIds = array_intersect($allow_client_ids, $this->config['force_client_ids']);
  171. if (!$tabid && count($this->allowForceClientIds)) {
  172. return true;
  173. }
  174. $client_id = $this->getClientArg('client_id');
  175. if (!in_array($client_id, $allow_client_ids)) {
  176. return false;
  177. }
  178. } else {
  179. $this->allowForceClientIds = $this->config['force_client_ids'];
  180. }
  181. return true;
  182. }
  183. protected function getClientArg($name)
  184. {
  185. static $args = [];
  186. $key = 'HTTP_USER_AGENT';
  187. if (isset($_SERVER['HTTP_SOCKETLOG'])) {
  188. $key = 'HTTP_SOCKETLOG';
  189. }
  190. if (!isset($_SERVER[$key])) {
  191. return;
  192. }
  193. if (empty($args)) {
  194. if (!preg_match('/SocketLog\((.*?)\)/', $_SERVER[$key], $match)) {
  195. $args = ['tabid' => null];
  196. return;
  197. }
  198. parse_str($match[1], $args);
  199. }
  200. if (isset($args[$name])) {
  201. return $args[$name];
  202. }
  203. return;
  204. }
  205. /**
  206. * @param string $host - $host of socket server
  207. * @param string $message - 发送的消息
  208. * @param string $address - 地址
  209. * @return bool
  210. */
  211. protected function send($host, $message = '', $address = '/')
  212. {
  213. $url = 'http://' . $host . ':' . $this->port . $address;
  214. $ch = curl_init();
  215. curl_setopt($ch, CURLOPT_URL, $url);
  216. curl_setopt($ch, CURLOPT_POST, true);
  217. curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
  218. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  219. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
  220. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  221. $headers = [
  222. "Content-Type: application/json;charset=UTF-8",
  223. ];
  224. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); //设置header
  225. return curl_exec($ch);
  226. }
  227. }