ThinkPHP6全链路追踪:分布式请求监控与性能分析实战

2025-07-13 0 1,001

ThinkPHP6全链路追踪:分布式请求监控与性能分析实战

一、全链路追踪核心架构

分布式系统请求监控的完整解决方案:

// 链路追踪中间件
namespace appmiddleware;

class TraceMiddleware
{
    public function handle($request, Closure $next)
    {
        // 生成唯一TraceID
        $traceId = $this->generateTraceId();
        
        // 记录开始时间
        $startTime = microtime(true);
        
        // 注入上下文
        $request->traceId = $traceId;
        thinkfacadeLog::withContext(['trace_id' => $traceId]);
        
        try {
            $response = $next($request);
            
            // 记录响应日志
            $this->logRequest($request, $startTime);
            
            return $response;
        } catch (Exception $e) {
            // 记录异常日志
            $this->logError($request, $e, $startTime);
            throw $e;
        }
    }
    
    protected function generateTraceId()
    {
        return uniqid('', true) . bin2hex(random_bytes(4));
    }
    
    protected function logRequest($request, $startTime)
    {
        $data = [
            'method' => $request->method(),
            'path' => $request->pathinfo(),
            'status' => $response->getCode(),
            'duration' => round((microtime(true) - $startTime) * 1000, 2),
            'params' => $request->param()
        ];
        
        thinkfacadeLog::info('Request Completed', $data);
    }
}

核心价值:请求可视化故障定位性能分析日志关联

二、分布式追踪实现

1. 跨服务追踪

// HTTP客户端追踪封装
namespace appcommonservice;

class HttpClient
{
    public static function request($url, $options = [])
    {
        $traceId = request()->traceId;
        $spanId = self::generateSpanId();
        
        $headers = [
            'X-Trace-Id' => $traceId,
            'X-Span-Id' => $spanId,
            'X-Parent-Span-Id' => request()->spanId ?? $traceId
        ];
        
        // 记录调用开始
        thinkfacadeLog::info('HTTP Call Start', [
            'url' => $url,
            'span_id' => $spanId
        ]);
        
        try {
            $response = thinkfacadeHttp::withHeaders($headers)
                ->timeout(10)
                ->send($url, $options);
                
            // 记录调用成功
            thinkfacadeLog::info('HTTP Call Success', [
                'url' => $url,
                'status' => $response->getCode(),
                'duration' => $response->getData('duration')
            ]);
            
            return $response;
        } catch (Exception $e) {
            // 记录调用失败
            thinkfacadeLog::error('HTTP Call Failed', [
                'url' => $url,
                'error' => $e->getMessage()
            ]);
            throw $e;
        }
    }
}

2. 数据库操作追踪

// 数据库监听器
namespace applistener;

class DbTrace
{
    public function handle($event)
    {
        $sql = $event->sql;
        $time = $event->time;
        $traceId = request()->traceId ?? 'N/A';
        
        // 记录慢查询
        if ($time > 500) {
            thinkfacadeLog::warning('Slow Query', [
                'sql' => $sql,
                'time' => $time,
                'trace_id' => $traceId
            ]);
        }
        
        // 记录所有查询
        thinkfacadeDb::listen(function($sql, $time) use ($traceId) {
            thinkfacadeLog::debug('SQL Query', [
                'sql' => $sql,
                'time' => $time,
                'trace_id' => $traceId
            ]);
        });
    }
}

// 注册监听器
thinkfacadeEvent::listen('DbQuery', DbTrace::class);

三、性能分析与可视化

1. 追踪数据存储与分析

// 追踪数据模型
namespace appmodel;

use thinkModel;

class Trace extends Model
{
    protected $table = 'traces';
    
    // 记录追踪数据
    public static function record($data)
    {
        self::create([
            'trace_id' => $data['trace_id'],
            'service_name' => config('app.name'),
            'start_time' => $data['start_time'],
            'end_time' => $data['end_time'],
            'duration' => $data['duration'],
            'status' => $data['status'],
            'operation' => $data['operation'],
            'tags' => json_encode($data['tags']),
            'logs' => json_encode($data['logs'])
        ]);
    }
    
    // 查询追踪链
    public static function getTraceChain($traceId)
    {
        return self::where('trace_id', $traceId)
            ->order('start_time', 'asc')
            ->select();
    }
}

// 可视化展示路由
Route::get('trace/view/:trace_id', function($traceId) {
    $spans = Trace::getTraceChain($traceId);
    return view('trace/view', ['spans' => $spans]);
});

四、生产环境最佳实践

  • 采样策略:生产环境按比例采样避免性能影响
  • 存储优化:使用Elasticsearch存储海量追踪数据
  • 告警机制:设置慢请求自动告警阈值
  • 安全考虑:敏感参数脱敏处理
  • 性能开销:监控追踪系统自身资源消耗
ThinkPHP6全链路追踪:分布式请求监控与性能分析实战
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

淘吗网 thinkphp ThinkPHP6全链路追踪:分布式请求监控与性能分析实战 https://www.taomawang.com/server/thinkphp/316.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务