1- # Laravel Audit Logger
2-
3- [ ![ Latest Version on Packagist] ( https://img.shields.io/packagist/v/iamfarhad/laravel-audit-log.svg?style=flat-square )] ( https://packagist.org/packages/iamfarhad/laravel-audit-log )
4- [ ![ GitHub Tests Action Status] ( https://img.shields.io/github/workflow/status/iamfarhad/laravel-audit-log/run-tests?label=tests )] ( https://github.com/iamfarhad/laravel-audit-log/actions?query=workflow%3Arun-tests+branch%3Amain )
5- [ ![ GitHub Code Style Action Status] ( https://img.shields.io/github/workflow/status/iamfarhad/laravel-audit-log/Check%20&%20fix%20styling?label=code%20style )] ( https://github.com/iamfarhad/laravel-audit-log/actions?query=workflow%3A"Check+%26+fix+styling"+branch%3Amain )
6- [ ![ Total Downloads] ( https://img.shields.io/packagist/dt/iamfarhad/laravel-audit-log.svg?style=flat-square )] ( https://packagist.org/packages/iamfarhad/laravel-audit-log )
1+ # Laravel Audit Log
72
83A comprehensive entity-level audit logging package for Laravel with support for MySQL and MongoDB databases.
94
10- ## Table of Contents
11-
12- - [ Features] ( #features )
13- - [ Requirements] ( #requirements )
14- - [ Installation] ( #installation )
15- - [ Configuration] ( #configuration )
16- - [ Basic Usage] ( #basic-usage )
17- - [ Making Models Auditable] ( #making-models-auditable )
18- - [ Automatic Logging] ( #automatic-logging )
19- - [ Manual Logging] ( #manual-logging )
20- - [ Retrieving Audit Logs] ( #retrieving-audit-logs )
21- - [ Disabling Auditing] ( #disabling-auditing )
22- - [ Advanced Features] ( #advanced-features )
23- - [ Custom Metadata] ( #custom-metadata )
24- - [ Field Filtering] ( #field-filtering )
25- - [ Batch Processing] ( #batch-processing )
26- - [ Custom Causer Resolver] ( #custom-causer-resolver )
27- - [ Using Different Drivers] ( #using-different-drivers )
28- - [ Event-Driven Architecture] ( #event-driven-architecture )
29- - [ Database Schema] ( #database-schema )
30- - [ Troubleshooting] ( #troubleshooting )
31- - [ Performance Considerations] ( #performance-considerations )
32- - [ Testing] ( #testing )
33- - [ Changelog] ( #changelog )
34- - [ License] ( #license )
35-
365## Features
376
387- ✅ ** Multiple Entity Support** : Audit any number of entities with dedicated log tables/collections
@@ -41,8 +10,6 @@ A comprehensive entity-level audit logging package for Laravel with support for
4110- ✅ ** Field Inclusion/Exclusion** : Fine-grained control over which fields to audit
4211- ✅ ** Causer Identification** : Automatic tracking of who made the changes
4312- ✅ ** Auto-Migration** : Automatic table/collection creation for new entities
44- - ✅ ** Batch Processing** : Optional batching of audit logs for improved performance
45- - ✅ ** Queue Support** : Option to process audit logs via Laravel queues
4613- ✅ ** SOLID Principles** : Clean, maintainable, and extensible architecture
4714
4815## Requirements
@@ -104,13 +71,6 @@ return [
10471 // Auto-migration for new entities
10572 'auto_migration' => env('AUDIT_AUTO_MIGRATION', true),
10673
107- // Batch processing configuration
108- 'batch' => [
109- 'enabled' => env('AUDIT_BATCH_ENABLED', false),
110- 'size' => env('AUDIT_BATCH_SIZE', 50),
111- 'timeout' => env('AUDIT_BATCH_TIMEOUT', 10), // seconds
112- ],
113-
11474 // Global field configuration
11575 'fields' => [
11676 'exclude' => ['password', 'remember_token', 'api_token'],
@@ -130,42 +90,45 @@ return [
13090
13191### Making Models Auditable
13292
133- To make a model auditable, implement the ` AuditableInterface ` and use the ` Auditable ` trait:
93+ To make a model auditable, simply use the ` Auditable ` trait:
13494
13595``` php
13696<?php
13797
138- declare(strict_types=1);
139-
14098namespace App\Models;
14199
142- use iamfarhad\LaravelAuditLog\Contracts\AuditableInterface;
143100use iamfarhad\LaravelAuditLog\Traits\Auditable;
144101use Illuminate\Database\Eloquent\Model;
145102
146- class Product extends Model implements AuditableInterface
103+ class Product extends Model
147104{
148105 use Auditable;
149106
150- // Your model code...
151-
107+ // Simply define properties to configure auditing
108+
152109 /**
153- * Get fields to exclude from audit logging.
110+ * Fields to exclude from audit logging.
154111 *
155- * @return array<string >
112+ * @var array<string >
156113 */
157- public function getAuditExclude(): array
158- {
159- return [
160- 'internal_notes',
161- 'updated_at',
162- ];
163- }
114+ protected array $auditExclude = [
115+ 'password',
116+ 'remember_token',
117+ 'updated_at',
118+ ];
119+
120+ /**
121+ * Fields to include in audit logging.
122+ * Default ['*'] means include all fields except excluded ones.
123+ * If you specify fields here, only these fields will be audited.
124+ *
125+ * @var array<string >
126+ */
127+ protected array $auditInclude = ['*'];
164128
165129 /**
166130 * Get custom metadata for audit logs.
167- *
168- * @return array<string , mixed >
131+ * Optional - Override this method to add custom metadata.
169132 */
170133 public function getAuditMetadata(): array
171134 {
@@ -174,14 +137,6 @@ class Product extends Model implements AuditableInterface
174137 'user_agent' => request()->userAgent(),
175138 ];
176139 }
177-
178- /**
179- * Determine if auditing should be queued.
180- */
181- public function shouldQueueAudit(): bool
182- {
183- return true; // Process audit logs in queue
184- }
185140}
186141```
187142
@@ -235,8 +190,6 @@ $logs = AuditLogger::getLogsForEntity(
235190 'action' => 'updated',
236191 'from_date' => '2024-01-01',
237192 'to_date' => '2024-12-31',
238- 'order_by' => 'created_at',
239- 'order_direction' => 'desc',
240193 ]
241194);
242195```
@@ -260,6 +213,32 @@ $product->enableAuditing();
260213
261214## Advanced Features
262215
216+ ### Field Filtering
217+
218+ Control which fields are audited using properties:
219+
220+ ``` php
221+ // Exclude specific fields
222+ protected array $auditExclude = [
223+ 'password',
224+ 'remember_token',
225+ 'secret_key'
226+ ];
227+
228+ // Or explicitly include only certain fields
229+ protected array $auditInclude = [
230+ 'name',
231+ 'email',
232+ 'role',
233+ 'status'
234+ ];
235+ ```
236+
237+ The field filtering works as follows:
238+ 1 . If ` $auditInclude ` is ` ['*'] ` (default), all fields except those in ` $auditExclude ` will be audited
239+ 2 . If ` $auditInclude ` has specific fields, only those fields (minus any in ` $auditExclude ` ) will be audited
240+ 3 . Global exclusions from ` config('audit-logger.fields.exclude') ` are always applied
241+
263242### Custom Metadata
264243
265244Add context to your audit logs by implementing ` getAuditMetadata() ` :
@@ -276,53 +255,6 @@ public function getAuditMetadata(): array
276255}
277256```
278257
279- ### Field Filtering
280-
281- Control which fields are audited:
282-
283- ``` php
284- // Exclude specific fields
285- protected array $auditExclude = ['password', 'remember_token', 'secret_key'];
286-
287- // Or explicitly include only certain fields
288- protected array $auditInclude = ['name', 'email', 'role', 'status'];
289-
290- // You can also implement getAuditExclude() or getAuditInclude() methods
291- // for more dynamic control
292- public function getAuditExclude(): array
293- {
294- $fields = ['password', 'remember_token'];
295-
296- if (!auth()->user()->isAdmin()) {
297- $fields[] = 'admin_notes';
298- }
299-
300- return $fields;
301- }
302- ```
303-
304- ### Batch Processing
305-
306- Enable batch processing in your config to improve performance:
307-
308- ``` php
309- // In config/audit-logger.php
310- 'batch' => [
311- 'enabled' => env('AUDIT_BATCH_ENABLED', true),
312- 'size' => env('AUDIT_BATCH_SIZE', 50),
313- 'timeout' => env('AUDIT_BATCH_TIMEOUT', 10), // seconds
314- ],
315- ```
316-
317- With batching enabled, audit logs are stored in memory and written to the database in batches. You can manually flush the batch:
318-
319- ``` php
320- use iamfarhad\LaravelAuditLog\Facades\AuditLogger;
321-
322- // Manually flush the batch
323- AuditLogger::flush();
324- ```
325-
326258### Custom Causer Resolver
327259
328260Create a custom causer resolver if you need special logic for determining who made a change:
@@ -370,25 +302,49 @@ AuditLogger::driver('mongodb')->log(...);
370302AuditLogger::driver('mysql')->log(...);
371303```
372304
373- ### Event-Driven Architecture
305+ ### Helper Methods for Retrieving Logs
374306
375- The package uses Laravel events. You can listen for audit events :
307+ You can add helper methods to your models to make retrieving audit logs easier :
376308
377309``` php
378- // In a service provider
379- use iamfarhad\LaravelAuditLog\Events\ModelAudited;
380- use Illuminate\Support\Facades\Event;
381-
382- Event::listen(ModelAudited::class, function (ModelAudited $event) {
383- // Access event properties
384- $entity = $event->entity;
385- $action = $event->action;
386- $oldValues = $event->oldValues;
387- $newValues = $event->newValues;
388-
389- // Your custom logic
390- // For example, send notifications, update cache, etc.
391- });
310+ /**
311+ * Get the audit logs for this model.
312+ */
313+ public function auditLogs(array $options = [])
314+ {
315+ return AuditLogger::getLogsForEntity(
316+ entityType: static::class,
317+ entityId: $this->getKey(),
318+ options: $options
319+ );
320+ }
321+
322+ /**
323+ * Get the most recent audit logs for this model.
324+ */
325+ public function recentAuditLogs(int $limit = 10)
326+ {
327+ return AuditLogger::getLogsForEntity(
328+ entityType: static::class,
329+ entityId: $this->getKey(),
330+ options: [
331+ 'limit' => $limit,
332+ 'from_date' => now()->subDays(30)->toDateString(),
333+ ]
334+ );
335+ }
336+
337+ /**
338+ * Get audit logs for a specific action.
339+ */
340+ public function getActionLogs(string $action)
341+ {
342+ return AuditLogger::getLogsForEntity(
343+ entityType: static::class,
344+ entityId: $this->getKey(),
345+ options: ['action' => $action]
346+ );
347+ }
392348```
393349
394350## Database Schema
@@ -409,28 +365,14 @@ CREATE TABLE audit_products_logs (
409365 metadata JSON NULL ,
410366 created_at TIMESTAMP NOT NULL ,
411367 INDEX idx_entity_id (entity_id),
412- INDEX idx_action (action),
413- INDEX idx_created_at (created_at),
414- INDEX idx_causer (causer_type, causer_id),
415- INDEX idx_entity_created (entity_id, created_at),
416- INDEX idx_entity_action (entity_id, action)
368+ INDEX idx_causer_id (causer_id),
369+ INDEX idx_created_at (created_at)
417370);
418371```
419372
420373### MongoDB
421374
422- For MongoDB, collections are created with appropriate indexes:
423-
424- ``` php
425- // Collection: audit_products_logs
426- // Indexes:
427- // - entity_id: 1
428- // - action: 1
429- // - created_at: 1
430- // - causer_type: 1, causer_id: 1
431- // - entity_id: 1, created_at: 1
432- // - entity_id: 1, action: 1
433- ```
375+ For MongoDB, collections are created with similar fields and appropriate indexes.
434376
435377## Troubleshooting
436378
@@ -450,44 +392,14 @@ For MongoDB, collections are created with appropriate indexes:
450392 ```
451393
4523942 . ** Logs not appearing** : Check if:
453- - Model implements ` AuditableInterface `
454395 - Model uses ` Auditable ` trait
455396 - Auditing is enabled on the model instance
456- - Batch processing might be holding logs (call ` AuditLogger::flush() ` )
457- - Check if queue is running (if using queued audits)
458397
4593983 . ** MongoDB driver issues** : Ensure you've installed the MongoDB package:
460399 ``` bash
461400 composer require mongodb/laravel-mongodb
462401 ```
463402
464- ### Debugging
465-
466- Enable debug mode in your Laravel application to see more information about audit logging:
467-
468- ``` php
469- // In .env
470- APP_DEBUG=true
471- ```
472-
473- ## Performance Considerations
474-
475- - Use batch processing for high-volume applications
476- - Consider using queued listeners for audit events (implement ` shouldQueueAudit() ` )
477- - Create appropriate indexes if you have custom query patterns
478- - Regularly archive old audit logs
479- - For extremely high-volume applications, consider a separate database for audit logs
480-
481- ## Testing
482-
483- ``` bash
484- composer test
485- ```
486-
487- ## Changelog
488-
489- Please see [ CHANGELOG] ( CHANGELOG.md ) for more information on what has changed recently.
490-
491403## License
492404
493405The MIT License (MIT). Please see [ License File] ( LICENSE.md ) for more information.
0 commit comments