how to create a middleware In laravel 10 to log all API request & response in database table?

huangapple go评论129阅读模式
英文:

how to create a middleware In laravel 10 to log all API request & response in database table?

问题

我在Laravel Lumen上有一个API项目,已经构建了大约300个API URL。现在的要求是将每个请求和其响应存储到数据库中以跟踪API调用。是否有任何包或简短的解决方案可以在不直接更改任何API函数或逐个更改的情况下进行存储?

英文:

I have an API project on Laravel lumen which is already built with approx 300 API URLs. Now the requirement is to store every request and its response to the database to track the API calls.
There is any package or short solution for that to store it without changing any API function directly or one by one?

答案1

得分: 1

您可以使用一个中间件来包装所有您的请求。

```php
class LoggerMiddleware
{
    public function handle($request, Closure $next)
    {
        try {
            $response = $next($request);

            $this->logSuccess($request, $response);

            return $response;
        } catch (Exception $ex) {
            $this->logFailure($request, $ex);
            throw $ex;
        }
    }

    public function logSuccess($request, $response)
    {
        // 记录到数据库
    }

    public function logFailure($request, $exception)
    {
        // 记录到数据库
    }
}

在 Laravel 中,将您的中间件添加到 App\Http\Kernelroutes/*.phpApp\Providers\RouteServiceProvider 中。

在 Lumen 中,您应该像这样注册您的中间件:
https://lumen.laravel.com/docs/10.x/middleware#registering-middleware

// bootstrap/app.php

$app->middleware([
   App\Http\Middleware\LoggerMiddleware::class
]);
英文:

You could use a middleware what wraps around all your requests.

class LoggerMiddleware
{
    public function handle($request, Closure $next)
    {
        try {
            $response = $next($request);

            $this->logSuccess($request, $response);

            return $response;
        } catch (Exception $ex) {
            $this->logFailure($request, $ex);
            throw $ex;
        }
    }

    public function logSuccess($request, $response)
    {
        // Log to database
    }

    public function logFailure($request, $exception)
    {
        // Log to database
    }
}

In Laravel add your middleware in App\Http\Kernel and routes/*.php or App\Providers\RouteServiceProvider

In Lumen you should register your middleware like this instead:
https://lumen.laravel.com/docs/10.x/middleware#registering-middleware

// bootstrap/app.php

$app->middleware([
   App\Http\Middleware\LoggerMiddleware::class
]);

huangapple
  • 本文由 发表于 2023年6月19日 18:09:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定