This package provides event logging for HTTP requests and model events. It is provider-agnostic and supports pluggable transports. The initial provider implementation ships an Azure Event Hub sender.
- Laravel 12
- PHP 8.4
- Azure Event Hub subscription
composer require codebar-ag/laravel-event-logsphp artisan vendor:publish --provider="CodebarAg\\LaravelEventLogs\\LaravelEventLogsServiceProvider"This will publish the configuration file to config/laravel-event-logs.php where you can customize the package settings.
If you want to customize the migrations or need them in your application's database/migrations directory, you can publish them:
php artisan vendor:publish --tag=laravel-event-logs-migrationsNote: Migrations are automatically loaded from the package, so publishing is optional. However, if you plan to use the event-logs:schema:create command, it's recommended to publish the migrations first, or the command will automatically publish them for you.
By default, the package uses your application's default database connection. You can specify a custom database connection for event logs by setting the connection option in your configuration file:
// config/laravel-event-logs.php return [ 'enabled' => env('EVENT_LOGS_ENABLED', false), 'connection' => env('EVENT_LOGS_CONNECTION', null), // Set to null to use default connection // ... other configuration ];Or via environment variable:
EVENT_LOGS_CONNECTION=event_logs_dbThis is useful when you want to store event logs in a separate database for better performance or isolation.
The package provides Artisan commands to manage the event logs database schema:
Create the database schema for event logs:
php artisan event-logs:schema:createThis command will:
- Check if the event logs connection is configured
- Verify if the
event_logstable already exists - Run the migration to create the
event_logstable if it doesn't exist - Automatically publish migrations if they haven't been published yet
Note: The command requires the connection configuration to be set. If not configured, the command will fail with an error message. If migrations are not published, the command will automatically publish them before running the migration.
Drop the database schema for event logs:
php artisan event-logs:schema:dropOr with the force option (no confirmation):
php artisan event-logs:schema:drop --forceThis command will:
- Check if the event logs connection is configured
- Verify if the schema exists
- Drop the
event_logstable if it exists
Warning: This will permanently delete all event logs data. Use with caution.
The EventLogMiddleware automatically logs all HTTP requests. Add it to your Laravel 12 application:
// config/laravel-event-logs.php return [ 'enabled' => env('EVENT_LOGS_ENABLED', false), 'connection' => env('EVENT_LOGS_CONNECTION', null), 'exclude_routes' => [ 'livewire.update', ], 'sanitize' => [ 'request_headers_exclude' => [ 'authorization', 'cookie', 'x-csrf-token', ], 'request_data_exclude' => [ 'password', 'password_confirmation', 'token', ], ], 'providers' => [ 'azure_event_hub' => [ 'endpoint' => env('AZURE_EVENT_HUB_ENDPOINT'), 'path' => env('AZURE_EVENT_HUB_PATH'), 'policy_name' => env('AZURE_EVENT_HUB_POLICY_NAME', 'RootManageSharedAccessKey'), 'primary_key' => env('AZURE_EVENT_HUB_PRIMARY_KEY'), ], ], ];// bootstrap/app.php use CodebarAg\\LaravelEventLogs\\Middleware\\EventLogMiddleware; return Application::configure(basePath: dirname(__DIR__)) ->withMiddleware(function (Middleware $middleware) { $middleware->web(append: [ EventLogMiddleware::class, ]); }) ->create();The middleware logs these HTTP request details:
- Request Information: Method, URL, route name, IP address
- Request User: Authenticated user type and ID
- Request Data: Sanitized headers and payload
- Context: Application context information
// Using AzureEventHubDTO::toArray() [ 'uuid' => '550e8400-e29b-41d4-a716-446655440000', 'type' => 'http_request', 'subject_type' => null, 'subject_id' => null, 'user_type' => 'App\Models\User', 'user_id' => 456, 'request_route' => 'users.store', 'request_method' => 'POST', 'request_url' => 'https://example.com/api/users', 'request_ip' => '192.168.1.100', 'request_headers' => ['Content-Type' => 'application/json'], 'request_data' => ['name' => 'John', 'email' => 'john@example.com'], 'event' => null, 'event_data' => null, 'context' => ['locale' => 'de_CH', 'environment' => 'production'], 'created_at' => '2024-01-15 10:30:00' ]The package provides an action to send event logs to Azure Event Hub. You can process events in background jobs for better performance.
Add your Azure Event Hub credentials to the published config file under providers.azure_event_hub:
// config/laravel-event-logs.php return [ 'enabled' => env('EVENT_LOGS_ENABLED', false), 'providers' => [ 'azure_event_hub' => [ 'endpoint' => env('AZURE_EVENT_HUB_ENDPOINT'), 'path' => env('AZURE_EVENT_HUB_PATH'), 'policy_name' => env('AZURE_EVENT_HUB_POLICY_NAME', 'RootManageSharedAccessKey'), 'primary_key' => env('AZURE_EVENT_HUB_PRIMARY_KEY'), ], ], ];AZURE_EVENT_HUB_ENDPOINT=https://your-namespace.servicebus.windows.net AZURE_EVENT_HUB_PATH=your-event-hub-name AZURE_EVENT_HUB_POLICY_NAME=RootManageSharedAccessKey AZURE_EVENT_HUB_PRIMARY_KEY=your-primary-key(new AzureEventHubAction())->send(EventLog $eventLog): void: Sends a singleCodebarAg\LaravelEventLogs\Models\EventLogto Azure Event Hub using the REST API. The payload is the model'stoArray()encoded as JSON and sent to.../messages?api-version=2014-01with a SAS token in theAuthorizationheader. Guard calls withconfig('laravel-event-logs.enabled')and handle idempotency (e.g.,synced_at`) in your job.
Minimal usage example:
use CodebarAg\LaravelEventLogs\Actions\AzureEventHubAction; use CodebarAg\LaravelEventLogs\Models\EventLog; // Send one event (instance API) (new AzureEventHubAction())->send($eventLog); // $eventLog is an instance of EventLogCreate a job to process and send event logs to Azure Event Hub:
<?php namespace App\Jobs; use CodebarAg\LaravelEventLogs\Actions\AzureEventHubAction; use CodebarAg\LaravelEventLogs\Models\EventLog; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; class ProcessAzureEventJob implements ShouldQueue { use Queueable; public function __construct( private EventLog $eventLog ) {} public function handle(): void { $enabled = config('laravel-event-logs.enabled'); if (! $enabled) { return; } if ($this->eventLog->synced_at) { return; } (new AzureEventHubAction())->send($this->eventLog); $this->eventLog->update([ 'synced_at' => now(), ]); } public function failed(\Throwable $exception): void { $this->eventLog->update([ 'synced_at' => null, ]); } }Use the HasEventLogTrait to automatically log model events (created, updated, deleted, restored).
<?php namespace App\Models; use CodebarAg\LaravelEventLogs\Traits\HasEventLogTrait; use Illuminate\Database\Eloquent\Model; class User extends Model { use HasEventLogTrait; // Your model code... }The trait automatically logs these events:
created: When a model is createdupdated: When a model is updateddeleted: When a model is deletedrestored: When a soft-deleted model is restored (if using SoftDeletes)
Each model event logs:
- Event type (created, updated, deleted, restored)
- Model class and ID
- User who triggered the event
- Model attributes (for created events)
- Changes made (for updated events)
- Original values (for updated events)
- Dirty keys (for updated events)
- Context information
// Using AzureEventHubDTO::toArray() when a User model is created: [ 'uuid' => '550e8400-e29b-41d4-a716-446655440000', 'type' => 'model', 'subject_type' => 'App\Models\User', 'subject_id' => '123', 'user_type' => 'App\Models\User', 'user_id' => 456, 'request_route' => null, 'request_method' => null, 'request_url' => null, 'request_ip' => null, 'request_headers' => null, 'request_data' => null, 'event' => 'created', 'event_data' => [ 'event' => 'created', 'model_type' => 'App\Models\User', 'model_id' => 123, 'attributes' => ['name' => 'John', 'email' => 'john@example.com'], 'changes' => [], 'original' => [], 'dirty_keys' => [], ], 'context' => ['tenant_id' => 1], 'created_at' => '2024-01-15 10:30:00' ]Use Laravel's Context facade to add custom context that will be included in all event logs. For example: create a middleware to set context before the EventLogMiddleware runs:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Context; class SetRequestContext { public function handle(Request $request, Closure $next) { // Add request context Context::add('locale', app()->getLocale()); return $next($request); } }Register the context middleware before EventLogMiddleware:
// bootstrap/app.php use App\Http\Middleware\SetRequestContext; use CodebarAg\LaravelEventLogs\Middleware\EventLogMiddleware; return Application::configure(basePath: dirname(__DIR__)) ->withMiddleware(function (Middleware $middleware) { $middleware->web(append: [ SetRequestContext::class, EventLogMiddleware::class, ]); }) ->create();