Skip to content

Instantly share code, notes, and snippets.

@aniket-magadum
Last active April 4, 2024 15:37
Show Gist options
  • Save aniket-magadum/947cd07329dfb618a9c04dfdd425dfc8 to your computer and use it in GitHub Desktop.
Save aniket-magadum/947cd07329dfb618a9c04dfdd425dfc8 to your computer and use it in GitHub Desktop.
RequestHandled Event in Laravel
<?php
namespace App\Providers;
use Event;
use Log;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Event::listen(RequestHandled::class, function (RequestHandled $event) {
// Ignore logging requests when request has no content for e.g Preflight, OPTION request
if(!method_exists($event->response,'content')){
return;
}
$responseSizeInBytes = strlen($event->response->content());
// Log requests with a response size above 1MB
if ($responseSizeInBytes > 1 * 1024 * 1024) {
$responseSizeInMB = round($responseSizeInBytes / (1024 * 1024), 2);
Log::info("Request URL: {$event->request->url()} | Response size: {$responseSizeInMB} MB");
}
$durationInMs = floor((microtime(true) - LARAVEL_START) * 1000);
// Log requests taking more than 2 seconds to complete
if ($durationInMs > 2000) {
$durationInSeconds = $durationInMs / 1000;
Log::info("Request URL: {$event->request->url()} | Duration: {$durationInSeconds} seconds");
}
$peakMemoryUsage = memory_get_peak_usage(true);
// Log requests consuming more than 10MB of RAM
if ($peakMemoryUsage > 10 * 1024 * 1024) {
$peakMemoryUsageInMB = round($peakMemoryUsage / (1024 * 1024), 2);
Log::info("Request URL: {$event->request->url()} | Peak memory usage: {$peakMemoryUsageInMB} MB");
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment