Skip to content

Instantly share code, notes, and snippets.

@MrPunyapal
Last active December 4, 2023 07:57
Show Gist options
  • Save MrPunyapal/008ed0f5d92c796a01c88d0ab3e5212a to your computer and use it in GitHub Desktop.
Save MrPunyapal/008ed0f5d92c796a01c88d0ab3e5212a to your computer and use it in GitHub Desktop.
Laravel Activity Logging with Events and Subscribers

Usage Instructions

Copy the Subscriber

  • Copy the contents of ActivityLogEventSubscriber.php into your Laravel project, typically in the app/Listeners directory.

Register the Subscriber

  • Register the ActivityLogEventSubscriber in your EventServiceProvider:
protected $subscribe = [
    \App\Listeners\ActivityLogEventSubscriber::class,
];

Customize Logging

  • Customize the log data based on specific requirements.
  • Include additional context, user information, or other relevant details.
<?php
namespace App\Listeners;
use Illuminate\Events\Dispatcher;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Console\Events\CommandFinished;
use Illuminate\Http\Client\Events\ResponseReceived;
use Illuminate\Support\Facades\Log;
class ActivityLogEventSubscriber
{
public function handleHttpRequest(RequestHandled $event): void
{
// Log activity for HTTP requests
$this->logActivity('RequestHandled', [
'request' => $event->request->toArray(),
'response' => $event->response->toArray(),
]);
}
public function handleConsoleCommand(CommandFinished $event): void
{
// Log activity for console commands
$this->logActivity('CommandFinished', [
'command' => $event->command,
'exitCode' => $event->exitCode,
]);
}
public function handleHttpClientResponse(ResponseReceived $event): void
{
// Log activity for HTTP client responses
$this->logActivity('ResponseReceived', [
'request' => $event->request->toArray(),
'response' => $event->response->toArray(),
]);
}
private function logActivity(string $eventType, array $eventData): void
{
// You can customize the log data based on their specific requirements
// For example, You may want to include additional context, user information, or any other relevant details.
Log::info("Activity Log: $eventType - " . json_encode($eventData));
}
public function subscribe(Dispatcher $events): array
{
return [
RequestHandled::class => 'handleHttpRequest',
CommandFinished::class => 'handleConsoleCommand',
ResponseReceived::class => 'handleHttpClientResponse',
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment