如何将请求和请求中的SQL绑定一起输出在详情里,而不是另外去写一个mysql上报中间件 如图
自己已解决了。分享给大家
<?php declare(strict_types=1); namespace app\market\middleware; use Closure; use GuzzleHttp\Client; use think\Request; use think\Response; class Transfer { /** * @var array */ public $sqlLogs = []; /** * 处理请求 * * @param Request $request * @param Closure $next * @return Response */ public function handle(Request $request, Closure $next) { static $initialized; if (!$initialized) { if (class_exists(\think\facade\Db::class)) { \think\facade\Db::listen(function ($sql, $runtime, $master) { if (!is_numeric($runtime)) { return; } $this->sqlLogs[] = trim($sql) . " [ RunTime: " . $runtime * 1000 . " ms ]"; }); } $initialized = true; } $startTime = microtime(true); // 开始时间 $project = 'TP6'; // 应用名 $ip = $this->getRealIP(); // 请求IP $controller = $request->controller(); $action = $request->action(); $transfer = $controller . '::' . $action; // 调用入口 $response = $next($request); $finishTime = microtime(true); // 结束时间 $costTime = $finishTime - $startTime; // 运行时长 $code = $response->getCode(); // 状态码 $success = $code < 400; // 是否成功 // 详细信息,自定义设置 $details = [ 'ip' => $this->getRealIP(), // 请求客户端IP 'url' => $request->Url() ?? '', // 请求URL 'method' => $request->method() ?? '', // 请求方法 'request_param' => $request->all() ?? [], // 请求参数 'request_server' => $request->server(), 'response_body' => $response->getData(), 'response_code' => $response->getCode() ?? '', 'time' => date('Y-m-d H:i:s.', (int)$startTime) . substr((string)$startTime, 11), // 请求时间(包含毫秒时间) 'run_time' => $costTime, // 运行时长 'sql' => $this->sqlLogs, // ..... ]; // 执行上报 try { // 数据打包 多条“\n”隔开 $data = json_encode([ 'time' => date('Y-m-d H:i:s.', (int)$startTime) . substr((string)$startTime, 11), 'project' => $project, 'ip' => $ip, 'transfer' => $transfer, 'costTime' => $costTime, 'success' => $success ? 1 : 0, 'code' => $code, 'details' => json_encode($details, 320), ], 320) . "\n"; $client = new Client(['verify' => false]); $client->post( // 上报地址 'http://0.0.0.0:8788/report/statistic/transfer', [ 'headers' => [ // 上报认证,不设置默认为当前年份的md5值 'authorization' => md5(date('Y')) ], 'form_params' => [ // 上报数据 'transfer' => $data ], ] ); } catch (\Throwable $th) { //throw $th; } return $response; } //客户端IP public function getRealIP(){ $forwarded = request()->header("x-forwarded-for"); if($forwarded){ $ip = explode(',',$forwarded)[0]; }else{ $ip = request()->ip(); } return $ip; } }
自己已解决了。分享给大家