Logging Request and Response with Controller and Function Name


by Samarth Sinha on 2017-04-30 11:51:19

Logging is one of the most powerful tools in software development. It gives you an idea of what your code is doing. In Laravel handling logs is very easy.

When you start a new Laravel project, error and exception handling is already configured for you. The App\Exceptions\Handler class is where all exceptions triggered by your application are logged and then rendered back to the user.

I have been working on how I can get Controller Name and Action on every url hit to know which controller function is being executed also I will log every Request and Response. For that I have made a middleware which will perform the above task.


namespace App\Http\Middleware;

use Log;
use Closure;
use Illuminate\Routing\Route;

class LogAfterRequest
    private $route;

    function __construct(Route $route)
        $this->route = $route;

    private function logs($value, $array = [])
        Log::info($value, $array);

    public function handle($request, Closure $next)
        $this->logs("Route controller and action: ". $this->route->getActionName());
        return $next($request);

    public function terminate($request, $response)
        $this->logs('Application Request:', ['request' => $request->all()]);
        $this->logs('Application Response:', ['response' => $response]);

About the Author

  • avatar
    Samarth Sinha

    My name Samarth Sinha. I work on developing Web Applications using PHP and MySQL and in different frameworks of PHP like Laravel, CakePHP, CodeIgnitor and Smarty. In databases I have worked in MySQL and Postgres. I started this blog to share my knowledge to those who wants to start developing Web Applications using PHP.