LARAVEL:如何为所有日志创建id并记录在容器中

问题描述 投票:0回答:1

嗨我想知道我是否可以为laravel项目中的所有日志生成id并在容器中记录id,我之前尝试创建一个中间件文件:

public function handle(Request $request, Closure $next): Response
    {
        $requestId = (string) Str::uuid();
 
        Log::shareContext([
            'request-id' => $requestId
        ]);

并将这个中间文件注册到kernel.php文件中,我想问是否有其他方法可以不在每个日志中生成id,我可以在全局方法中生成日志id吗?非常感谢!

我尝试在每个日志中生成id。

laravel laravel-8
1个回答
0
投票

这是您可以做到的方法。

创建一个中间件,而不是尝试修改每个日志语句,您可以创建一个生成唯一标识符并将其附加到日志上下文的中间件。该中间件将为每个传入请求执行,确保该请求中的每个日志共享相同的标识符。

enter code here

注册中间件您可以全局注册此中间件,以便它适用于所有传入请求。

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;

class LogRequestId
{
    public function handle($request, Closure $next)
    {
        $requestId = (string) Str::uuid();

        // Share the request ID with the log context
        Log::setDefaultDriver('request'); // Use the appropriate log channel if needed
        Log::info('New request', ['request-id' => $requestId]);

        // Attach the request ID to the request for future use if needed
        $request->requestId = $requestId;

        return $next($request);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.