英文:
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\Kernel
和 routes/*.php
或 App\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
]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论