How to log every response in laravel 5.2 framework

2019-05-07 01:11发布

问题:

I was using below code for logging each and every request and response for my API but now it's not working for Laravel 5.2.

I have tried to use https://laravel.com/docs/5.2/middleware#terminable-middleware but not succeed.

use Closure;  
use Illuminate\Contracts\Routing\TerminableMiddleware;  
use Illuminate\Support\Facades\Log;

class LogAfterRequest implements TerminableMiddleware {

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

    public function terminate($request, $response)
    {
        $logFile = 'log.txt';
        Log::useDailyFiles(storage_path().'/logs/'.$logFile);
        Log::info('app.requests', ['request' => $request->all(), 'response' => $response->getContent()]);
    }

}

Can anyone suggest me the solution?

回答1:

Assuming you use web group for your routes.php, you should add in app/Kernel.php in $middlewareGroups for web the following middleware:

\App\Http\Middleware\LogAfterRequest ::class,

Your routes.php should look like this:

Route::group(['middleware' => 'web'], function () {
  // here you put all the routes
});


回答2:

I have got the solution. the issue was that i have added "die" in controller method due to which terminate function is not executing and so no log generated.