mysql链路跟踪工具_EasySwoole利用链路追踪组件制作甩锅工具
前言
最近前端老是反饋API調用異常,說請求成功但是沒有數據返回!
我寫的代碼怎么可能有bug,肯定是前端調用的方式不對!
經過一番套鼓,直接把請求參數和響應內容打印到控制臺,果然不出我所料,請求缺少重要參數!
為了能讓前端每次出問題后不用來找我(俗稱甩鍋),自己排查問題,我就想著把每次的請求參數和響應內容記錄下來,前端查看請求記錄詳情排查問題。
剛好看到EasySwoole有這么一個組件(鏈路追蹤)可以記錄每次的請求信息,所以就寫了這個甩鍋工具。(說真的用起來真香)
話不多說先來一張甩鍋工具效果圖
每次請求需要記錄的參數
請求地址、客戶端IP、請求時間、請求狀態、請求耗時、請求參數、響應內容
先創建mysql表CREATE TABLE `td_api_tracker_point_list` (
`pointd` varchar(18) NOT NULL,
`ip` varchar(100) DEFAULT '',
`create_date` varchar(30) DEFAULT '' COMMENT '訪問時間 2020-02-23 12:00:00',
`pointName` varchar(100) DEFAULT NULL,
`parentId` varchar(18) DEFAULT NULL,
`depth` int(11) NOT NULL DEFAULT '0',
`isNext` int(11) NOT NULL DEFAULT '0',
`startTime` varchar(14) NOT NULL,
`endTime` varchar(14) DEFAULT NULL,
`spendTime` decimal(15,3) DEFAULT '0.000',
`status` varchar(10) NOT NULL,
`uri` varchar(255) DEFAULT '',
`result` text,
`data` text,
PRIMARY KEY (`pointd`),
UNIQUE KEY `trackerId_UNIQUE` (`pointd`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
創建ORM表模型
\App\Model\TrackerPoint\TrackerPointModel.php<?php
namespaceApp\Model\TrackerPoint;classTrackerPointModelextends\EasySwoole\ORM\AbstractModel
{protected$tableName='td_api_tracker_point_list';}
就是這么簡單就創建好了表模型
安裝鏈路追蹤組件composer require easyswoole/tracker
使用鏈路追蹤
在EasySwooleEvent.php的onRequest引入鏈路追蹤并傳入請求uri,get和post參數public static functiononRequest(Request$request,Response$response): bool
{$allow_origin=array("http://www.xxx1.com","https://www.xxxx2.com","http://127.0.0.1",);$origin=$request->getHeader('origin');if($origin!== []){$origin=$origin[0];if(in_array($origin,$allow_origin)){$response->withHeader('Access-Control-Allow-Origin',$origin);$response->withHeader('Access-Control-Allow-Methods','GET, POST, OPTIONS');$response->withHeader('Access-Control-Allow-Credentials','true');$response->withHeader('Access-Control-Allow-Headers','Content-Type, Authorization, X-Requested-With, token');if($request->getMethod() ==='OPTIONS') {$response->withStatus(Status::CODE_OK);return false;}
}
}/**
* 鏈路追蹤
*/$point= PointContext::getInstance()->createStart($request->getUri()->__toString());$point->setStartArg(['uri'=>$request->getUri()->__toString(),'get'=>$request->getQueryParams(),'post'=>$request->getRequestParam()
]);return true;}
在EasySwooleEvent.php的afterRequest獲取鏈路結果并寫入到mysql表中//請求結束前執行public static functionafterRequest(Request$request,Response$response): void{// 真實IP$ip='';if(count($request->getHeader('x-real-ip'))) {$ip=$request->getHeader('x-real-ip')[0];}else{$params=$request->getServerParams();foreach(['http_client_ip','http_x_forward_for','x_real_ip','remote_addr']as$key) {if(isset($params[$key]) && !strcasecmp($params[$key],'unknown')) {$ip=$params[$key];break;}}}// 查看每次請求記錄 http://host/index/tracker$point= PointContext::getInstance()->startPoint();$point->end();$array= Point::toArray($point);$rsp=$response->getBody();foreach($arrayas$k=>$v){$data['ip'] =$ip;$data['pointd'] =$v['pointId'];$data['pointName'] =$v['pointName'];$data['parentId'] =$v['parentId'];$data['depth'] =$v['depth'];$data['isNext'] =$v['isNext'];$data['startTime'] =$v['startTime'];$data['endTime'] =$v['endTime'];$data['spendTime'] =$v['endTime']-$v['startTime'];$data['status'] =$v['status'];$data['result'] = json_encode($v);$data['data'] =$rsp->__tostring();$data['uri'] =$v['startArg']['uri'];$data['create_date'] = date('Y-m-d H:i:s',time());if(strpos($v['startArg']['uri'],'index/tracker') !==false||strpos($v['startArg']['uri'],'index/tracker') !==false){//過濾index/tracker和index/getTracker這兩個方法}else{\App\Model\TrackerPoint\TrackerPointModel::create()->data($data,false)->save();}}}
到這里基本大功告成了,剩下的就是寫個頁面把記錄展示出來
安裝模板視圖composer require easyswoole/template
實現渲染引擎
創建文件\App\Template.php<?php
namespace App;
use EasySwoole\Template\RenderInterface;
class Template implements RenderInterface
{
protected $template;
function __construct()
{
$config = [
'view_path' ? ?=> EASYSWOOLE_ROOT.'/App/Views/',
'cache_path' ? => EASYSWOOLE_ROOT.'/Temp/runtime/',
];
$this->template = new \think\Template($config);
}
public function render(string $template, array $data = [], array $options = []): ?string
{
// TODO: Implement render() method.
ob_start();
$this->template->assign($data);
$this->template->fetch($template);
$content = ob_get_contents() ;
return $content;
}
public function afterRender(?string $result, string $template, array $data = [], array $options = [])
{
// TODO: Implement afterRender() method.
}
public function onException(\Throwable $throwable): string
{
// TODO: Implement onException() method.
$msg = "{$throwable->getMessage()} at file:{$throwable->getFile()} line:{$throwable->getLine()}";
trigger_error($msg);
return $msg;
}
}
在EasySwooleEvent.php的mainServerCreate實例化視圖并注入配置/*** **************** ? 實例化該Render,并注入你的驅動配置 ? ?*****************/Render::getInstance()->getConfig()->setRender(newTemplate());Render::getInstance()->attachServer(ServerManager::getInstance()->getSwooleServer());
在http控制器中使用視圖模板渲染,存放模板的目錄App/Views/index
控制器文件\App\HttpController\Index.php<?phpnamespaceApp \HttpController;useApp\Model\TrackerPoint\TrackerPointModel;useApp\Utility\MyQueue;useEasySwoole\Component\AtomicManager;useEasySwoole\Component\Timer;useEasySwoole\EasySwoole\Logger;useApp\Model\WechatModel;useEasySwoole\Http\AbstractInterface\Controller;useEasySwoole\ORM\DbManager;useEasySwoole\Queue\Job;useEasySwoole\Template\Render;useEasySwoole\Tracker\PointContext;useElasticsearch\ClientBuilder;use\Swoole\Coroutineasco;useEasySwoole\Mysqli\QueryBuilder;useEasySwoole\Jwt\Jwt;use\PhpOffice\PhpSpreadsheet\Spreadsheet;use\PhpOffice\PhpSpreadsheet\Writer\Xlsx;classIndexextendsController{protected functiononRequest(?string$action): ?bool{return true;}//渲染模板public functiontracker(){$this->response()->write(Render::getInstance()->render('index/tracker',['row'=> time(),'json'=>json_encode([])]));}//獲取鏈路記錄列表public functiongetTracker(){$model= TrackerPointModel::create();$param=$this->request()->getRequestParam();if(!empty($param['uri']) ){$model->where('uri',"%{$param['uri']}%",'like');}$limit=$param['limit']??10;$p=$param['page']??1;$data['code'] =0;$data['msg'] ='';$list=$model->withTotalCount()->limit($p* ($p-1),$limit)->order('pointd','desc')->select();$data['count'] =$model->lastQueryResult()->getTotalCount();foreach($listas$k=>$v){$uri= explode(':9501/',$v['uri']);if(count($uri)!=2){$uri= explode(':80/',$v['uri']);}$list[$k]['uri'] = !empty($uri[1])?$uri[1]:$v['uri'];$result= json_decode($v['result'],true);unset($result['startArg']['uri']);$list[$k]['result'] = json_encode($result['startArg']);if(strpos($v['uri'],'tracker') !==false||strpos($v['uri'],'getTracker') !==false){$list[$k]['data'] ='';}}$data['data'] =$list;$data['sql'] =$model->lastQuery()->getLastPrepareQuery();$this->response()->write(json_encode($data));return false;}
//測試計數器functionindex(){$this->response()->withHeader('Content-type','text/html;charset=utf-8');$atomic= AtomicManager::getInstance()->get('second');$atomic->add(1);echodate('i:s',time()).'計數器:'.$atomic->get().PHP_EOL;$this->response()->write('計數器:'.$atomic->get().PHP_EOL);}}
甩鍋完畢
最后甩鍋工具完成,直接丟鏈接給前端? http://你的域名:9501/index/tracker
本文為夠意思原創文章,轉載無需和我聯系,但請注明來自夠意思博客blog.go1s.cn:夠意思博客 ? EasySwoole利用鏈路追蹤組件制作甩鍋工具
總結
以上是生活随笔為你收集整理的mysql链路跟踪工具_EasySwoole利用链路追踪组件制作甩锅工具的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3000元 谷歌Pixel 5a屏幕翻车
- 下一篇: 2022年最美骁龙8+手机来袭 real