I want to save all api logs in db. For example whenever a api gets hit, its request and response get saved in a table.
Is there settings in Lavavel to enable logs of Rest apis into db.
For example in codeigniter: Request param logs as : a:12:{s:13:"session_token";s:20:"OiCtWkqBLm6ScaSHOmQR";s:12:"Content-Type";s:16:"application/json";s:13:"cache-control";s:8:"no-cache";s:13:"Postman-Token";s:36:"0d13fe2e-9986-4ef2-ba46-8207dd28cd44";s:10:"User-Agent";s:20:"PostmanRuntime/7.1.1";s:6:"Accept";s:3:"/";s:4:"Host";s:9:"localhost";s:6:"cookie";s:81:"PHPSESSID=ho1oa4gjll59u4vq9usct3lev7; ci_session=ruttt4i5144hob6feq3mrv080nh2n74o";s:15:"accept-encoding";s:13:"gzip, deflate";s:14:"content-length";s:2:"19";s:10:"Connection";s:10:"keep-alive";s:7:"user_id";i:13;}
If you want to build something yourself, terminable middleware is a great solution in Laravel. This type of middleware is executed after all the heavy work is done (request & reponses handled, etc.).
Add a new model to store your LogEntries in. Create your migrations, etc. This is basis Laravel stuff I will not explain... :-)
Then, to start off with the middleware, create a middleware class like this:
$ php artisan make:middleware RequestLoggerMiddleware
Add a body to the new class:
class RequestLoggerMiddleware
{
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate(Request $request, Response $response)
{
$logEntry = new LogEntry();
$logEntry->attribute = VALUE;
$logEntry->attribute = VALUE;
$logEntry->attribute = VALUE;
$logEntry->attribute = VALUE;
$logEntry->save();
}
}
Add the middleware to your Kernel.php:
protected $middleware = [
...
RequestLoggerMiddleware::class,
...
];
In the Middleware you can add tons of stuff to your attributes. The injected reponse and request have a lot of information in them:
request start time >> date('Y-m-d H:i:s', LARAVEL_START)
URL >> request->fullUrl()
request HTTP method >> $request->method()
request body >> json_decode($request->getContent(), true);
request header >> $request->header();
ip >> $request->ip()
status code >> $response->getStatusCode()
request body >> json_decode($response->getContent(), true);
BTW this is an EXAMPLE of a code structure you could use, to give you an basic idea about the solution. Obviously, you need to add the correct attributes to the model, the migrations, etc. But I am sure you can handle that part...
And: inject the Model in the constructor instead the above example... :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With