Laravel 5: Logging all requests and responses

It’s important when deploying a new platform to monitor the first few interactions and keep an eye out for unintended issues.

Logging requests and responses against the server is a great way to get a birds eye view of the action.

With Laravel 5, this is best done with middleware.

  1. Create a clean git branch to do this work on 🙂
  2. Create the LogAfterRequest.php middleware file, in App\Http\Middleware\LogAfterRequest.php, and paste the following contents:
    <?php
    namespace App\Http\Middleware;
    
    use Illuminate\Support\Facades\Log;
    class LogAfterRequest {
        public function handle($request, \Closure $next)
        {
            return $next($request);
        }
        public function terminate($request, $response)
        {
          $url=$request->fullUrl();
          $ip=$request->ip();
          $r=new \App\Models\Request();
          $r->ip=$ip;
          $r->url=$url;
          $r->request=json_encode($request->all());
          $r->response=$response;
          $r->save();
        }
    }
  3. Wire up the middleware in App\Http\Kernel.php
    protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\LogAfterRequest::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];
  4. Create a migration to hold the requests/responses in your database, and create a model to pass to the database.
     php artisan make:migration log_requests_responses
     php artisan make:model Models/Request
  5. Add the following structure to the new migrations file in app/database/migrations:
    public function up()
    {
    Schema::create("requests",function(Blueprint $table){
     $table->increments("id");
     $table->text("request");
     $table->text("response");
     $table->string("url", 1024);
     $table->string("ip", 16);
     $table->timestamps();
    });
    }
  6. run php artisan migrate and check that the requests are recording.
  7. Be super careful about this code finding its way to production and for how long.
    There’s a real cost to your page load if storing all of this in your database, and huge security implications to storing whole requests/responses (such as live tokens, passwords).
    Also, you should be aware of XSS implications of storing/retrieving unsanitized inputs (as we are above)
  8. You should make further adjustments to the logging code to scrub tokens and passwords at the very least.
Published