Download the PHP package iamfarhad/laravel-audit-log without Composer
On this page you can find all versions of the php package iamfarhad/laravel-audit-log. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download iamfarhad/laravel-audit-log
More information about iamfarhad/laravel-audit-log
Files in iamfarhad/laravel-audit-log
Package laravel-audit-log
Short Description Comprehensive entity-level audit logging package for Laravel applications with model-specific tables, field exclusion, and batch processing support
License MIT
Informations about the package laravel-audit-log
Laravel Audit Logger
Overview
Laravel Audit Logger is a powerful and flexible package designed to provide comprehensive audit logging for Laravel applications. It enables tracking of all changes to your Eloquent models with advanced features including source tracking, queue processing, and customizable field management, ensuring compliance with regulatory requirements, aiding in debugging, and maintaining data integrity. Built with modern PHP and Laravel practices, this package adheres to strict typing, PSR-12 coding standards, and leverages dependency injection for maximum testability and maintainability.
The package uses a high-performance direct logging architecture with optional queue integration, making it suitable for both small applications and enterprise-scale systems.
Table of Contents
- Features
- Requirements
- Installation
- Configuration
- Usage
- Basic Usage
- Advanced Usage
- Source Tracking
- Queue Processing
- Customizing Audit Logging
- Retrieving Audit Logs
- Performance Optimization
- Testing
- Security Best Practices
- Audit Log Retention
- Migration & Upgrade Guide
- Troubleshooting
- Contributing
- License
Features
- Entity-Specific Audit Tables: Automatically creates dedicated tables for each audited model to optimize performance and querying.
- Comprehensive Change Tracking: Logs all CRUD operations (create, update, delete, restore) with old and new values.
- Advanced Source Tracking: Automatically tracks the source of changes (console commands, HTTP routes, background jobs) for enhanced debugging and compliance.
- Queue Processing: Supports both synchronous and asynchronous audit log processing for improved performance.
- Customizable Field Management: Control which fields to include or exclude from auditing with global and model-specific configurations.
- User Tracking: Automatically identifies and logs the user (causer) responsible for changes with configurable guard and resolver support.
- Direct Logging Architecture: Uses direct service calls for high-performance logging with optional event integration.
- Batch Processing: Supports batch operations for high-performance logging in large-scale applications.
- Type Safety: Built with PHP 8.1+ strict typing, readonly properties, and modern features.
- Enhanced Query Scopes: Comprehensive filtering capabilities with dedicated scopes for different query patterns.
- Extensible Drivers: Supports multiple storage drivers (currently MySQL) with the ability to implement custom drivers.
- Automatic Migration: Seamlessly creates audit tables for new models when enabled.
- Smart Retention System: Comprehensive retention policies with delete, anonymize, and archive strategies for compliance and performance.
- Static Analysis: Level 5 PHPStan compliance for maximum code quality and reliability.
Requirements
- PHP: 8.1 or higher
- Laravel: 10.x, 11.x, or 12.x
- Database: MySQL 8.0+ (for the default driver)
Installation
Install the package via Composer:
After installation, publish the configuration file to customize settings:
This will create a configuration file at config/audit-logger.php
where you can adjust settings like the storage driver, table naming conventions, queue processing, and more.
Configuration
The configuration file config/audit-logger.php
allows you to customize the behavior of the audit logger. Below are the key configuration options:
Environment Variables
You can use environment variables to configure the audit logger:
Database Schema
The audit logger creates tables with the following structure for each audited model:
The source
field is automatically populated to track the origin of changes:
- Console commands: Command name (e.g.,
app:send-emails
) - HTTP requests: Controller action (e.g.,
App\Http\Controllers\UserController@update
) - Background jobs: Job class name
- Queue workers: Queue job processing context
Usage
Basic Usage
To make a model auditable, simply add the Auditable
trait to your Eloquent model. Ensure strict typing is enabled as per the engineering rules.
Once the trait is added, any changes to the model (create, update, delete, restore) will be automatically logged to a dedicated audit table (e.g., audit_orders_logs
).
Authenticated User Tracking
The audit logger automatically tracks WHO made the change and WHERE it came from:
Retrieving Audit Logs with User Information
You can easily retrieve audit logs with user information:
Advanced User Tracking Examples
Example 1: Track User Changes in Controller
Example 2: Track System Changes in Console Commands
Example 3: Custom Metadata with User Context
Example 4: Querying Audit Logs by User and Source
Configuration for User Tracking
The causer (user) resolution can be configured in the config/audit-logger.php
file:
Custom Causer Resolver
You can create a custom causer resolver for complex scenarios:
Register your custom resolver in a service provider:
Excluding Fields
To exclude specific fields from being audited, define the $auditExclude
property:
Including Specific Fields
Alternatively, you can specify only the fields to audit using $auditInclude
:
Advanced Usage
Custom Metadata
You can enrich audit logs with custom metadata by implementing the getAuditMetadata
method in your model:
Source Tracking
The audit logger automatically tracks the source of changes to help with debugging and compliance. The source field captures:
- Console Commands: Artisan command names (e.g.,
app:send-emails
,migrate
,queue:work
) - HTTP Routes: Controller action names or route names for web requests
- Background Jobs: Job class names when changes occur within queued jobs
- Queue Workers: Processing context for queue-based operations
Enhanced Query Scopes for Source Filtering
Query audit logs by source using convenient scopes:
Temporarily Disabling Auditing
For specific operations where auditing is not required, you can disable it temporarily:
Custom Audit Events with Fluent API
To log custom actions beyond standard CRUD operations, use the fluent API provided by the audit()
method:
This fluent interface provides:
- Better performance than event-driven architectures
- Direct database logging without event dispatch overhead
- Respects model's auditable attributes
- Merges default metadata from
getAuditMetadata()
with custom metadata - Maintains source tracking for custom events
Queue Processing
The audit logger supports both synchronous and asynchronous processing of audit logs for improved performance in high-traffic applications.
Enabling Queue Processing
Update your configuration to enable queue processing:
Or use environment variables:
Queue Jobs Architecture
The package includes two specialized queue jobs:
ProcessAuditLogJob
: Handles standard asynchronous audit log processingProcessAuditLogSyncJob
: Provides fallback synchronous processing when needed
Queue Configuration Options
enabled
: Boolean to enable/disable queue processing (default:false
)connection
: Queue connection to use (default: your app's default queue connection)queue_name
: Name of the queue to dispatch audit jobs to (default:audit
)delay
: Delay in seconds before processing the job (default:0
for immediate processing)
Benefits of Queue Processing
- Improved Performance: Audit logging doesn't block your application's main thread
- Scalability: Handle high-volume audit logging without impacting user experience
- Reliability: Failed audit logs can be retried automatically with Laravel's queue system
- Resource Management: Control when and how audit logs are processed
- Better Error Handling: Queue-specific error handling and monitoring
Queue Worker Setup
When using queue processing, ensure you have queue workers running:
For production environments, consider using Supervisor or similar process managers to keep your queue workers running reliably.
Customizing Audit Logging
Custom Driver Implementation
If you need to extend the audit logging functionality, you can implement a custom driver by adhering to the AuditDriverInterface
:
Register your custom driver in a service provider:
Custom Causer Resolver
You can implement a custom causer resolver for complex authentication scenarios:
Retrieving Audit Logs
Model Relationship
Audit logs are accessible via a relationship on the audited model:
Advanced Querying with EloquentAuditLog
For more complex queries, use the EloquentAuditLog
model directly with comprehensive scopes:
Available Query Scopes
The EloquentAuditLog
model provides comprehensive scopes for efficient filtering:
Entity and Basic Filtering
forEntity(string $entityClass)
- Filter by entity typeforEntityId($entityId)
- Filter by entity IDforAction(string|array $action)
- Filter by action(s)forCauser(string $causerClass)
- Filter by causer typeforCauserId($causerId)
- Filter by causer ID
Date Filtering
forCreatedAt($createdAt)
- Filter by exact creation datedateGreaterThan($date)
- Filter for logs after a specific datedateLessThan($date)
- Filter for logs before a specific datedateBetween($startDate, $endDate)
- Filter for logs within a date range
Enhanced Source Filtering
forSource(string $source)
- Filter by exact source matchfromConsole()
- Filter for logs from console commandsfromHttp()
- Filter for logs from HTTP requestsfromCommand(string $command)
- Filter by specific console commandfromController(?string $controller = null)
- Filter by controller
Performance Optimization
Database Optimization
- Automatic Indexing: The package automatically creates indexes on frequently queried columns (
entity_id
,causer_type
,causer_id
,created_at
,source
,action
) - Entity-Specific Tables: Each model gets its own audit table for optimal query performance
- JSON Column Usage: Efficiently stores old/new values and metadata using MySQL's native JSON support
Application-Level Optimization
- Queue Processing: Enable queue processing for high-traffic applications to improve response times
- Selective Auditing: Limit audited fields to only those necessary for compliance or debugging
- Batch Operations: Use the audit service's batch capabilities for bulk operations
- Strategic Field Exclusion: Configure global and model-specific field exclusions to reduce storage overhead
Recommended Configuration for High-Traffic Applications
Monitoring and Maintenance
Testing
This package includes a comprehensive test suite with high coverage. To run the tests locally:
Test Categories
The test suite includes:
-
Unit Tests: Test individual components in isolation
AuditLoggerServiceTest
: Service layer testingMySQLDriverTest
: Driver functionalityCauserResolverTest
: User identificationAuditableTraitTest
: Trait functionality
-
Feature Tests: Test integration between components
AuditLogIntegrationTest
: Full integration scenariosAuditLogBatchTest
: Batch processingCustomAuditActionTest
: Custom audit events
- Integration Tests: Test real-world scenarios with database
Testing Your Implementation
When writing tests for your application, ensure you cover audit logging behavior:
Security Best Practices
Data Protection
- Exclude Sensitive Data: Always exclude fields containing PII or sensitive data using
$auditExclude
or global configuration - Enhanced Security Fields: The package now excludes common sensitive fields by default (API keys, tokens, payment information)
- Metadata Sanitization: Be cautious about what data you include in custom metadata
Access Control
- Authorization Gates: Implement Laravel Gates or Policies to restrict access to audit logs
- Role-Based Access: Consider different access levels for different types of audit data
- API Protection: If exposing audit logs via API, ensure proper authentication and rate limiting
Data Retention and Compliance
- Retention Policies: Implement automated cleanup of old audit logs based on your compliance requirements
- GDPR Compliance: Consider implementing user data deletion when users request account deletion
- Export Capabilities: Provide audit trail export functionality for compliance reporting
Audit Log Retention
The Laravel Audit Logger package includes a powerful retention system that helps you manage the lifecycle of your audit logs. This system supports automatic cleanup, anonymization, and archiving of old audit data to help with compliance requirements and database performance.
Features
- Multiple Retention Strategies: Delete, anonymize, or archive old audit logs
- Per-Model Configuration: Override global settings for specific models
- Batch Processing: Efficient processing of large datasets
- Smart Anonymization: Automatically detect and anonymize sensitive fields
- Flexible Scheduling: Run manually or via scheduled jobs
- Dry Run Mode: Preview changes before execution
Configuration
Global Configuration
Configure retention settings in your config/audit-logger.php
:
Environment Variables
Per-Entity Configuration
Configure retention settings for specific entities:
Per-Model Configuration
Configure retention directly in your model:
Retention Strategies
1. Delete Strategy
Permanently removes old audit logs from the database.
Use Case: When you want to minimize storage usage and don't need historical data beyond a certain period.
2. Anonymize Strategy
Replaces sensitive information with anonymized values while keeping the audit structure intact.
Anonymized Fields: email, phone, address, ip_address, user_agent, name, first_name, last_name, full_name
Use Case: Compliance requirements where you need to maintain audit trail structure but remove personally identifiable information.
3. Archive Strategy
Moves old audit logs to a separate database connection for long-term storage.
Use Case: Long-term compliance requirements where you need to maintain historical data but keep the primary database lean.
4. Combined Strategy
You can combine anonymization with deletion or archiving:
Usage
Manual Execution
Queue Processing
Scheduled Execution
Add to your app/Console/Kernel.php
:
Service Usage
Best Practices
- Start with Dry Runs: Always test your retention policies with
--dry-run
before applying - Monitor Performance: Use appropriate batch sizes for your database performance
- Backup Strategy: Ensure you have backups before running retention operations
- Compliance Review: Review your retention policies with legal/compliance teams
- Gradual Implementation: Start with longer retention periods and adjust based on requirements
- Queue Processing: Use queued processing for large datasets to avoid timeouts
Security Considerations
- Access Control: Ensure only authorized users can execute retention commands
- Audit the Audit: Consider logging retention operations themselves
- Data Recovery: Have procedures for data recovery in case of mistakes
- Anonymization Verification: Test that anonymized data meets your privacy requirements
Migration & Upgrade Guide
Upgrading from Version 1.2.x to 1.3.x
Version 1.3.0 introduced breaking changes with the move from event-driven to direct logging architecture:
Breaking Changes
- Event System Removed:
ModelAudited
event andAuditModelChanges
listener have been removed - Direct Logging: The system now uses direct service calls instead of event dispatching
- Enhanced Configuration: New configuration options for causer resolution and entity management
Migration Steps
-
Update Configuration: Publish the new configuration file:
-
Database Schema: Add the
source
column to existing audit tables: -
Remove Event Listeners: If you were listening to
ModelAudited
events, replace with direct service usage or custom implementations. - Test Your Implementation: Ensure all audit logging continues to work as expected.
Upgrading from Version 1.1.x to 1.2.x
Version 1.2.0 introduced structural changes:
- DTO Introduction:
AuditLog
moved from Models to DTOs namespace - Enhanced EloquentAuditLog: New model with comprehensive scopes
- Improved Test Suite: Better test coverage and organization
Most changes are backward compatible, but you should update any direct references to the old AuditLog
model class.
Troubleshooting
Common Issues and Solutions
Audit Tables Not Created
- Solution: Ensure
'auto_migration' => true
in your configuration - Manual Creation: Use
AuditLogger::driver()->createStorageForEntity(Model::class)
Missing Logs
- Check Field Exclusion: Verify fields aren't excluded globally or in the model
- Auditing Status: Ensure auditing isn't disabled for the operation
- Queue Processing: If using queues, ensure workers are running
Causer Not Recorded
- Authentication: Confirm user is logged in during the operation
- Guard Configuration: Check the causer guard configuration
- Custom Resolver: Verify custom causer resolver implementation
Source Field Issues
- Console Commands: Ensure
$_SERVER['argv']
is available - HTTP Requests: Verify route is properly registered
- Context Detection: Check application is running in expected context
Queue Processing Issues
- Worker Status: Ensure queue workers are running:
php artisan queue:work --queue=audit
- Connection: Verify queue connection is properly configured
- Failed Jobs: Monitor with
php artisan queue:failed
- Debugging: Temporarily disable queues to test synchronous processing
Performance Issues
- Enable Queues: For high-traffic applications, enable queue processing
- Field Exclusion: Exclude non-essential fields to reduce storage overhead
- Database Optimization: Ensure proper indexing (handled automatically)
- Batch Operations: Use batch processing for bulk operations
Static Analysis Errors
- PHPStan: The package is PHPStan Level 5 compliant
- Dynamic Methods: Some warnings about dynamic method calls are expected and ignored
- Type Safety: Ensure strict typing is enabled in your models
Debug Mode
Enable debug logging to troubleshoot issues:
Getting Help
- Check Documentation: Review this README and the changelog
- Search Issues: Look through existing GitHub issues
- Create Issue: If you find a bug, create a detailed issue with:
- Laravel version
- PHP version
- Package version
- Minimal reproduction steps
- Expected vs actual behavior
Contributing
Contributions are welcome! Please follow these guidelines:
Development Setup
- Fork the Repository: Create your own fork of the project
- Clone Locally:
git clone your-fork-url
- Install Dependencies:
composer install
- Run Tests:
composer test
to ensure everything works
Code Standards
- PSR-12: Follow PSR-12 coding standards
- Strict Types: Use
declare(strict_types=1);
in all PHP files - Type Hints: Provide type hints for all parameters and return values
- PHPStan: Code must pass PHPStan Level 5 analysis
- Tests: Include tests for new features and bug fixes
Pull Request Process
- Create Branch: Create a feature branch from
main
- Write Code: Implement your changes following the code standards
- Add Tests: Include comprehensive tests for your changes
- Update Documentation: Update README and changelog as needed
-
Run Quality Checks:
- Submit PR: Create a detailed pull request with description of changes
Code Quality Tools
The project uses several quality assurance tools:
License
This package is open-sourced software licensed under the MIT license.
Laravel Audit Logger - Comprehensive audit logging for modern Laravel applications with advanced source tracking, queue processing, and enterprise-grade features.
All versions of laravel-audit-log with dependencies
illuminate/support Version ^10.0|^11.0|^12.0
illuminate/database Version ^10.0|^11.0|^12.0
illuminate/events Version ^10.0|^11.0|^12.0
illuminate/config Version ^10.0|^11.0|^12.0