Friday, April 8, 2016

Log every request & response in Laravel 5.1

Log every request & response in Laravel 5.1:

Sometimes it's useful to log some/all requests to your application. This is really convenient when you use Laravel to build your APIs.

A logging middleware might log all incoming requests to your application. In Laravel 5.1 there is a terminate method and it's call after the sending HTTP response to the browser. This way we have access to both $request and $response at the same time.

Let's take a look at how we are going to achieve this in Laravel 5.1:

Create a new middleware by type this command in terminal inside your project directory.

php artisan make:middleware LogAfterRequest

And then put below code in it(project_dir/app/Http/Middleware/LogAfterRequest.php).

<?php

namespace App\Http\Middleware;

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

class LogAfterRequest {

    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        Log::info('app.requests', ['request' => $request->all(), 'response' => $response]);
    }

}


In this code terminate method receives $request and $response. These are objects which will give you all of the handy stuffs you probably need to log.

When we have our middleware ready, we should add it to our HTTP Kernel.

Open Kernel.php and add this line to your protected $middleware property:

\App\Http\Middleware\LogAfterRequest::class

That's it. You can additionally filter what you want to actually log, but this is the basics.

Thanks.

No comments:

Post a Comment