Laravel 5: Logging all requests and responses • Code Workshop

Code Workshop
8/16/2018
Share with

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.

  • Create a clean git branch to do this work on 🙂

  • Create the LogAfterRequest.php middleware file, in App\Http\Middleware\LogAfterRequest.php, and paste the following contents:

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();
    }
}
  • 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,
];
  • 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
  • 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();
});
}
  • Run php artisan migrate and check that the requests are recording.

  • 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).

You should make further adjustments to the logging code to scrub tokens and passwords at the very least.