mysql链路跟踪工具_EasySwoole利用链路追踪组件制作甩锅工具

前言

最近前端老是反馈API调用异常,说请求成功但是没有数据返回!

我写的代码怎么可能有bug,肯定是前端调用的方式不对!

经过一番套鼓,直接把请求参数和响应内容打印到控制台,果然不出我所料,请求缺少重要参数!

为了能让前端每次出问题后不用来找我(俗称甩锅),自己排查问题,我就想着把每次的请求参数和响应内容记录下来,前端查看请求记录详情排查问题。

刚好看到EasySwoole有这么一个组件(链路追踪)可以记录每次的请求信息,所以就写了这个甩锅工具。(说真的用起来真香)

话不多说先来一张甩锅工具效果图

7170105d4ea3db68744f2a9f9df65c94.png

每次请求需要记录的参数

请求地址、客户端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

7170105d4ea3db68744f2a9f9df65c94.png

本文为够意思原创文章,转载无需和我联系,但请注明来自够意思博客blog.go1s.cn:够意思博客 » EasySwoole利用链路追踪组件制作甩锅工具

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/440807.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java selector 源码_Java NIO核心组件-Selector和Channel

昨天我们介绍了一下SelectorProvider和IO multiplexing.特别是IO multiplexing中的epoll系统调用,是Linux版本的Java的NIO的核心实现.那今天我们就来介绍一下, Java NIO中的核心组件, Selector和Channel.这两个组件,对于熟悉Java OIO,而不熟悉Java NIO的朋友来说,理解其作用是极…

python 爬虫 博客园_Python爬虫爬取博客园作业

分析一下他们的代码&#xff0c;我在浏览器中对应位置右键&#xff0c;然后点击检查元素&#xff0c;可以找到对应部分的代码。但是&#xff0c;直接查看当前网页的源码发现&#xff0c;里面并没有对应的代码。我猜测这里是根据服务器上的数据动态生成的这部分代码&#xff0c;…

java 与 xml_xml与java对象转换

public static void main(String[] args) {//java bean 转 xmlDept d new Dept();List staffs new ArrayList<>();Staff s1 new Staff("wuyun", 20);Staff s2 new Staff("lilei", 22);staffs.add(s1);staffs.add(s2);d.setDeptName("开放平…

【牛客 - 370H】Rinne Loves Dynamic Graph(分层图最短路)

题干&#xff1a; 链接&#xff1a;https://ac.nowcoder.com/acm/contest/370/H 来源&#xff1a;牛客网 Rinne 学到了一个新的奇妙的东西叫做动态图&#xff0c;这里的动态图的定义是边权可以随着操作而变动的图。 当我们在这个图上经过一条边的时候&#xff0c;这个图上所…

中位数及带权中位数问题(转)

先从一到简单的题看起&#xff1a; 士兵站队问题 在一个划分成网格的操场上&#xff0c;n个士兵散乱地站在网格点上。网格点由整数坐标(x,y)表示。士兵们可以沿网格边上、下、左、右移动一步&#xff0c;但在同一时刻任一网格点上只能有一名士兵。按照军官的命令&#xff0c;…

*【HDU - 4272 】LianLianKan (dfs 或 状压dp,贪心不行)

题干&#xff1a; I like playing game with my friend, although sometimes looks pretty naive. Today I invent a new game called LianLianKan. The game is about playing on a number stack. Now we have a number stack, and we should link and pop the same element…

java中的values函数_巧用valueat函数(快逸免费版)

在制作报表时&#xff0c;经常会遇到将数据库里一列数据按照条件取值后&#xff0c;分为多列显示的需求&#xff0c;例如&#xff1a;数据库中有一列名为type的数据&#xff0c;在报表中&#xff0c;第一列选择type为1的数据&#xff0c;第二列选择type为2的数据。由于受到扩展…

Java设计流程执行器_Java进阶面试精选系列:SpringMVC+SpringBoot+Hibernate+Mybatis+设计模式...

小编精心收集&#xff1a;为金三银四准备&#xff0c;以下面试题先过一遍&#xff0c;为即将到了的面试做好准备&#xff0c;也过一遍基础知识点。一、Spring/Spring MVC1.为什么要使用 spring&#xff1f;2.解释一下什么是 aop&#xff1f;3.解释一下什么是 ioc&#xff1f;3.…

【牛客 - 370E】Rinne Loves Gift(Bellman_Ford判负环,二分,分数规划)

题干&#xff1a; 链接&#xff1a;https://ac.nowcoder.com/acm/contest/370/E 来源&#xff1a;牛客网 Rinne 喜欢礼物&#xff0c;也喜欢送礼物 圣诞节快到了&#xff0c;Rinne 要去给给住在城市里的人送礼物 城市的交通可以抽象成一个 n 个点 m 条边的有向图 每条边上有…

【POJ - 2976】【ZOJ - 3068】【SCU - 2992】Dropping tests (01分数规划)

题干&#xff1a; In a certain course, you take n tests. If you get ai out of bi questions correct on test i, your cumulative average is defined to be . Given your test scores and a positive integer k, determine how high you can make your cumulative aver…

重写过的url 怎么获取当前页面url java_网站URL重写(Java UrlRewrite 的使用)

现在大部分的网站和商城都会使用到URL重写&#xff0c;接触到这个&#xff0c;也是因为正在做的电子商务商城。URL重写&#xff0c;是将原有的URL采用另一种规则来显示&#xff0c;使得用户方便访问同时也屏蔽一些信息。在此说下它的好处&#xff0c;在开发过程中&#xff0c;经…

Java行业情景分析_Java 设计模式情景分析——单例模式

单例模式可以说是应用最广的模式之一&#xff0c;在应用单例模式时&#xff0c;单例对象的类必须保证只有一个实例存在&#xff0c;而且可以自行实例化并向整个系统提供这个实例。一般在不能自由构造对象的情况下&#xff0c;就会使用单例设计模式&#xff0c;例如创建一个对象…

php实现播放直播_PHP直播技术分享(一:实现直播)

推流服务器采用的是自搭的推流服务器 , 自己玩玩 做外包项目还是去搞七牛云/阿里这样的服务器吧,开始bb-----1:技术栈image.jpeg2:开发中业务(1)主播申请时创建个秘钥 , 这个秘钥随时字符串即可到时候根据字符串找到拉流的直播位置存数据库包括推流地址image.png3:配置nginx-rt…

php获取location,php获取header[‘location’]信息常见问题

15/01/31本文关键字: 302, header, location//初始化url信息$host “#8221;;$url$host.”l/rzTf7ap2viw/&iid222004556&resourceId0_04_05_99/v.swf”;//按照字段获取header响应信息$headers get_headers($url, TRUE);//获取这个土豆的302跳转地址$u302 $headers[“Lo…

php对联广告,html左右对联代码 cms网站对联广告html代码

实现网页左右两侧居中的对联广告代码你只记得自己有好多朋友却从没想过小编只有你一人。无标题文档 #left{ width:200px;height:450px; position:absolute; left:0px; background:red; border:1px #000 solid} #right{width:200px;height:450px; position:absolute; right:0px;…

php 分页 url重写 分页问题,解决千古难题,wordpress分页URL问题,wordpress给分页加链接...

原本的wordpress文章如果分页会成如下的结构&#xff1a;http://www.xyqzmt.cn/1.html/2通常固定链接都是这样的结构&#xff0c;设为/%postname%.html或者/%post_id%.html 以前我一直无法解决如上的问题&#xff0c;最后放弃挣扎&#xff0c;如果遇到很长的文章全都放在一个页…

【牛客 - 181F】子序列(容斥,组合数,费马小定理)

题干&#xff1a; 题目描述 给出一个长度为n的序列&#xff0c;你需要计算出所有长度为k的子序列中&#xff0c;除最大最小数之外所有数的乘积相乘的结果 输入描述: 第一行一个整数T&#xff0c;表示数据组数。 对于每组数据&#xff0c;第一行两个整数N&#xff0c;k&#…

【CodeForces - 485C】Bits (二进制相关,数学,贪心)

题干&#xff1a; Lets denote as the number of bits set (1 bits) in the binary representation of the non-negative integer x. You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, an…

php工程导致系统蓝屏,经常蓝屏是什么原因

经常蓝屏的原因&#xff1a;1、错误安装或更新显卡驱动后导致电脑蓝屏&#xff1b;2、超频过度是导致蓝屏&#xff1b;3、安装的软件存在不兼容&#xff1b;4、电脑内部硬件温度过高&#xff1b;5、内存条接触不良或内存损坏。错误更新显卡驱动错误安装或更新显卡驱动后导致电脑…

【CodeForces - 485A】Factory (水题,抽屉原理,tricks)

题干&#xff1a; One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were x details in the factory storage, then by the end of the day the factory has to p…