API Logging using Middleware in Laravel

Chandresh
CS Code
Published in
2 min readMay 7, 2020

--

Photo by Maarten van den Heuvel on Unsplash

Have you ever been in situation when you wanted to log a specific API to debug an issue in running production application API?

Here is the easiest way to do that using middleware.

If you would like to watch it step by step then you can watch this tutorial.

Let’s start!

What is middleware?

Middleware provides a convenient mechanism for filtering HTTP requests entering your application.

You can think of middleware as a series of “layers” HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

Create a middleware using command

php artisan make:middleware LogRoute

Open LogRoute.php

It has a simple handle function here which is taking in request and passing it to next Closure.

Write your logic for the information about API that you want to log like this:

Open Kernel file. Assign a key log.route to your middleware.

protected $routeMiddleware = [
...
'log.route' => LogRoute::class
];

Open api.php

Set middleware on the route that you want to log.

Route::get('me', 'AuthController@me')->middleware('log.route');

That’s It!

Now try calling your API using a rest client like Postman or Any application consuming the API and you will see them being logged into your storage/logs/laravel.log file.

You can get the entire code here.

--

--