<?php
declare (strict_types = 1);

namespace app\admin\middleware\v1;

use think\facade\Event;
class RequestId
{
    public function handle($request, \Closure $next)
    {
        // 生成request_id
        $request_id = bin2hex(random_bytes(8));
        
        // 将request_id设置到请求属性中
        $request->request_id =  $request_id;
        header('X-Request-ID: ' . $request_id);
        
        Event::listen('think\event\LogWrite', function($event) use($request_id) {
            $event->log['request_id'] = $request_id;
        });
        
        
        return $next($request);
    }
}