PHPackages                             codebar-ag/laravel-event-logs - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. codebar-ag/laravel-event-logs

ActiveLibrary

codebar-ag/laravel-event-logs
=============================

Event logging for HTTP requests and model events with pluggable providers.

v12.6.0(1mo ago)04.3k[1 PRs](https://github.com/codebar-ag/laravel-event-logs/pulls)MITPHPPHP ^8.4CI passing

Since Aug 10Pushed 1mo agoCompare

[ Source](https://github.com/codebar-ag/laravel-event-logs)[ Packagist](https://packagist.org/packages/codebar-ag/laravel-event-logs)[ RSS](/packages/codebar-ag-laravel-event-logs/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (7)Dependencies (28)Versions (17)Used By (0)

Laravel Event Logs
==================

[](#laravel-event-logs)

[![Packagist Version](https://camo.githubusercontent.com/3e74f5f4616325c71a637d253f26f4457d6ace70890e06505e012be670001412/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f64656261722d61672f6c61726176656c2d6576656e742d6c6f67732e737667)](https://packagist.org/packages/codebar-ag/laravel-event-logs)[![Downloads](https://camo.githubusercontent.com/c3bc4752b3532a1f81de31bc4c21d04fc1979997c9875387442bf4c1714c6de0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636f64656261722d61672f6c61726176656c2d6576656e742d6c6f67732e737667)](https://packagist.org/packages/codebar-ag/laravel-event-logs/stats)[![License](https://camo.githubusercontent.com/9679a5bee1637aa2565e35d5efbb1bf654d1655e42e34da0f62f90ad77cae628/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f636f64656261722d61672f6c61726176656c2d6576656e742d6c6f67732e737667)](https://github.com/codebar-ag/laravel-event-logs/blob/main/LICENSE)[![PHP Version](https://camo.githubusercontent.com/be142a537aa070555060c23b338159532b6a0ff5f33b791cebddd4a9ef0f85e7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f636f64656261722d61672f6c61726176656c2d6576656e742d6c6f67733f6c6f676f3d706870266c6f676f436f6c6f723d7768697465)](https://packagist.org/packages/codebar-ag/laravel-event-logs)[![Laravel Version](https://camo.githubusercontent.com/b62a068237739cf707ba9f0082955564ece762b6fda1a65d09bd8da1a4269f9c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31322e782532422d4646324432303f6c6f676f3d6c61726176656c266c6f676f436f6c6f723d7768697465)](https://laravel.com)[![PEST](https://github.com/codebar-ag/laravel-event-logs/actions/workflows/pest.yml/badge.svg)](https://github.com/codebar-ag/laravel-event-logs/actions/workflows/pest.yml)[![PHPStan](https://github.com/codebar-ag/laravel-event-logs/actions/workflows/phpstan.yml/badge.svg)](https://github.com/codebar-ag/laravel-event-logs/actions/workflows/phpstan.yml)

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.

Table of Contents
-----------------

[](#table-of-contents)

- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
    - [Database Connection](#database-connection)
    - [Schema Management](#schema-management)
- [Usage](#usage)
    - [Middleware Request Logging](#middleware-request-logging)
    - [Model Event Logging](#model-event-logging)
    - [Sending Logs to Azure Event Hub](#sending-logs-to-azure-event-hub)
    - [Adding Context](#adding-context)

Requirements
------------

[](#requirements)

- Laravel 12
- PHP 8.4
- Azure Event Hub subscription

Installation
------------

[](#installation)

### Composer Install

[](#composer-install)

```
composer require codebar-ag/laravel-event-logs
```

### Publish Configuration

[](#publish-configuration)

```
php 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.

### Publish Migrations (Optional)

[](#publish-migrations-optional)

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-migrations
```

**Note**: 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.

Configuration
-------------

[](#configuration)

### Database Connection

[](#database-connection)

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_db
```

This is useful when you want to store event logs in a separate database for better performance or isolation.

### Schema Management

[](#schema-management)

The package provides Artisan commands to manage the event logs database schema:

#### Create Schema

[](#create-schema)

Create the database schema for event logs:

```
php artisan event-logs:schema:create
```

This command will:

- Check if the event logs connection is configured
- Verify if the `event_logs` table already exists
- Run the migration to create the `event_logs` table 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 Schema

[](#drop-schema)

Drop the database schema for event logs:

```
php artisan event-logs:schema:drop
```

Or with the force option (no confirmation):

```
php artisan event-logs:schema:drop --force
```

This command will:

- Check if the event logs connection is configured
- Verify if the schema exists
- Drop the `event_logs` table if it exists

**Warning**: This will permanently delete all event logs data. Use with caution.

Usage
-----

[](#usage)

### Middleware Request Logging

[](#middleware-request-logging)

The `EventLogMiddleware` automatically logs all HTTP requests. Add it to your Laravel 12 application:

#### Configuration

[](#configuration-1)

```
// 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'),
        ],
    ],
];
```

#### Implementation

[](#implementation)

```
// bootstrap/app.php
use CodebarAg\\LaravelEventLogs\\Middleware\\EventLogMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            EventLogMiddleware::class,
        ]);
    })
    ->create();
```

#### Logged Data

[](#logged-data)

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

#### Example Output

[](#example-output)

```
// 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'
]
```

### Sending Logs to Azure Event Hub

[](#sending-logs-to-azure-event-hub)

The package provides an action to send event logs to Azure Event Hub. You can process events in background jobs for better performance.

#### Configuration

[](#configuration-2)

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'),
        ],
    ],
];
```

#### Environment Variables

[](#environment-variables)

```
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
```

#### Available Methods

[](#available-methods)

- **`(new AzureEventHubAction())->send(EventLog $eventLog): void`**: Sends a single `CodebarAg\LaravelEventLogs\Models\EventLog` to Azure Event Hub using the REST API. The payload is the model's `toArray()` encoded as JSON and sent to `.../messages?api-version=2014-01` with a SAS token in the `Authorization` header`. Guard calls with `config('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 EventLog
```

#### Example Implementation

[](#example-implementation)

Create a job to process and send event logs to Azure Event Hub:

```
