1.Trace_id问题
若想实现全链路监控,必须由前端发起,从而实现一体化的监控。实现思路,主要是前端自己生成trace_id及其他必要的上下文参数。
经过摸索,x-b3-traceid生成规则如下,先生成8位随机字符串(0-9a-zA-Z) ,然后再转换成十六进制,如:30d7cab480f9193c 。
在框架中的源码实现方式如下:ctype_xdigit或者isValidTraceId可以用这个去查看是否符合规则
/**
* @return string
*/
function generateNextId(): string
{
return \bin2hex(\openssl_random_pseudo_bytes(8));
}
$nextId = '43766e39446a5254';
$result = ctype_xdigit($nextId);
$result2 = isValidTraceId($nextId);
vdump($result,$result2, $nextId, strlen($nextId));
亦可用如下的代码实现:
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = 8;
echo bin2hex(substr(str_shuffle(str_repeat($pool, 5)), 0, $length));
最后生成的效果是,
2.DBListener问题
笔者用的是swoft框架,所以只需监听 DdEvent::SQL_RAN 若是其他框架,自行捕捉db事件
废话不多说:上代码
<?php declare(strict_types=1);
namespace App\Listener;
use Swoft\Db\Connection\Connection;
use Swoft\Db\DbEvent;
use Swoft\Event\Annotation\Mapping\Listener;
use Swoft\Event\EventHandlerInterface;
use Swoft\Event\EventInterface;
use Swoft\Http\Server\HttpContext;
use Swoft\Log\Helper\CLog;
use const Zipkin\Kind\CLIENT;
use function Zipkin\Timestamp\now;
/**
* Class DbListener
* @package App\Listener
* @Listener(DbEvent::SQL_RAN)
*/
class DbListener implements EventHandlerInterface
{
/**
* SQL ran
*
* @param EventInterface $event
*
*/
public function handle(EventInterface $event): void
{
/** @var Connection $connect