litepie / logs
A comprehensive activity log package for Laravel applications
Fund package maintenance!
litepie.com/sponsor
Requires
- php: ^8.1
- illuminate/contracts: ^9.0|^10.0|^11.0
- illuminate/database: ^9.0|^10.0|^11.0
- illuminate/support: ^9.0|^10.0|^11.0
Requires (Dev)
- mockery/mockery: ^1.4
- orchestra/testbench: ^7.0|^8.0|^9.0
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^9.0|^10.0
This package is auto-updated.
Last update: 2025-08-23 07:13:18 UTC
README
A comprehensive and powerful activity logging package for Laravel applications that provides detailed tracking and auditing capabilities with enhanced foreign key resolution, batch operations, and advanced filtering.
Features
- ๐ Automatic Model Logging - Track model changes automatically with the
LogsActivity
trait - ๐ Enhanced Foreign Key Resolution - Automatically resolve foreign keys to human-readable names
- ๐ฆ Batch Operations - Group related activities with batch UUIDs
- โก Queue Support - Process logs asynchronously for better performance
- ๐๏ธ Database Partitioning - Monthly partitioning for large datasets
- ๐ก๏ธ Privacy Protection - Anonymize sensitive data and exclude fields
- ๐ Advanced Filtering - Rich querying and filtering capabilities
- ๐ Statistics & Analytics - Built-in activity statistics and reporting
- ๐ Export Functionality - Export logs in multiple formats (CSV, JSON, PDF)
- ๐ฏ Retention Policies - Configurable data retention with automatic cleanup
- ๐ API Support - Optional API routes for external access
- ๐งช Comprehensive Testing - Full test suite with PHPUnit
๐ Quick Start
1. Install the Package
composer require litepie/logs
2. Publish Configuration & Run Migrations
php artisan vendor:publish --provider="Litepie\Logs\LogsServiceProvider" --tag="config" php artisan migrate
3. Add the Trait to Your Model
use Litepie\Logs\Traits\LogsActivity; class User extends Model { use LogsActivity; protected $fillable = ['name', 'email']; }
4. That's It! ๐
All model changes are now automatically logged:
$user = User::create(['name' => 'John', 'email' => 'john@example.com']); // โ Logged: "User created" $user->update(['name' => 'Jane']); // โ Logged: "User updated" with change details $user->delete(); // โ Logged: "User deleted"
๐ Requirements
- PHP: 8.1, 8.2, or 8.3
- Laravel: 9.x, 10.x, or 11.x
- Database: MySQL 5.7+ (for partitioning features), PostgreSQL, SQLite
๐ Installation
Option 1: Quick Install (Recommended)
# Install the package composer require litepie/logs # Publish config and run migrations php artisan vendor:publish --provider="Litepie\Logs\LogsServiceProvider" --tag="config" php artisan migrate
Option 2: Custom Installation
# Install package composer require litepie/logs # Publish config file (optional) php artisan vendor:publish --provider="Litepie\Logs\LogsServiceProvider" --tag="config" # Publish migrations (if you want to customize) php artisan vendor:publish --provider="Litepie\Logs\LogsServiceProvider" --tag="migrations" # Run migrations php artisan migrate
๐ก Tip: The package will automatically register its service provider in Laravel 5.5+
Configuration
The configuration file config/logs.php
provides extensive customization options:
return [ // Enable/disable activity logging 'enabled' => env('ACTIVITY_LOG_ENABLED', true), // Default log name 'default_log_name' => env('ACTIVITY_LOG_DEFAULT_NAME', 'default'), // Database table name 'table_name' => env('ACTIVITY_LOG_TABLE_NAME', 'activity_logs'), // Automatic cleanup (days) 'delete_records_older_than_days' => env('ACTIVITY_LOG_DELETE_RECORDS_OLDER_THAN_DAYS', 365), // Queue settings 'queue_logs' => env('ACTIVITY_LOG_QUEUE_LOGS', false), 'queue_connection' => env('ACTIVITY_LOG_QUEUE_CONNECTION', 'default'), // Performance optimizations 'enable_partitioning' => env('ACTIVITY_LOG_ENABLE_PARTITIONING', false), 'batch_size' => env('ACTIVITY_LOG_BATCH_SIZE', 1000), // Privacy settings 'privacy' => [ 'anonymize_ip' => env('ACTIVITY_LOG_ANONYMIZE_IP', false), 'exclude_fields' => ['password', 'password_confirmation', 'remember_token'], 'hash_sensitive_data' => env('ACTIVITY_LOG_HASH_SENSITIVE', false), ], // And many more options... ];
Basic Usage
Automatic Model Logging
Add the LogsActivity
trait to any model you want to track:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Litepie\Logs\Traits\LogsActivity; class User extends Model { use LogsActivity; protected $fillable = ['name', 'email', 'status']; // Optional: Specify which events to log protected $logEvents = ['created', 'updated', 'deleted']; // Optional: Custom log name protected $logName = 'user-management'; }
Now all changes to your User model will be automatically logged:
$user = User::create(['name' => 'John Doe', 'email' => 'john@example.com']); // Automatically logs: "User created" $user->update(['name' => 'Jane Doe']); // Automatically logs: "User updated" with changes $user->delete(); // Automatically logs: "User deleted"
Enhanced Foreign Key Resolution
Automatically resolve foreign keys to human-readable names:
class User extends Model { use LogsActivity; protected $fillable = ['name', 'email', 'category_id', 'department_id']; // Configure which foreign keys should resolve their related model names protected $resolveRelations = [ 'category_id' => 'name', // Will store category name 'department_id' => 'title', // Will store department title 'manager_id' => 'full_name', // Will store manager's full name ]; // Optional: Custom field names for display protected $fieldNames = [ 'category_id' => 'Category', 'department_id' => 'Department', 'manager_id' => 'Manager', ]; public function category() { return $this->belongsTo(Category::class); } public function department() { return $this->belongsTo(Department::class); } }
When you update a user's category, the activity log will show:
- Instead of: "category_id changed from 1 to 2"
- You'll see: "Category changed from 'Technology' to 'Sales'"
Manual Activity Logging
Use the facade for manual logging:
use Litepie\Logs\Facades\ActivityLog; // Basic logging ActivityLog::log('User performed action'); // With properties ActivityLog::withProperties(['key' => 'value'])->log('Action performed'); // With subject and causer ActivityLog::performedOn($model) ->causedBy($user) ->withProperties(['details' => 'Additional info']) ->log('Model updated'); // Custom log name ActivityLog::useLog('security')->log('Security event occurred');
Batch Operations
Group related activities with batch UUIDs:
$batchUuid = ActivityLog::generateBatchUuid(); // Start batch ActivityLog::withBatch($batchUuid) ->causedBy(auth()->user()) ->log('Bulk operation started'); // Perform operations foreach ($users as $user) { $user->update($updates); ActivityLog::withBatch($batchUuid) ->performedOn($user) ->causedBy(auth()->user()) ->log("Updated user: {$user->name}"); } // End batch ActivityLog::withBatch($batchUuid) ->causedBy(auth()->user()) ->log('Bulk operation completed');
Advanced Features
Querying Activities
use Litepie\Logs\Helpers\ActivityLogger; // Get activities for a specific model $activities = ActivityLogger::forModel($user); // Get activities caused by a user $userActions = ActivityLogger::causedBy($user); // Get activities within a date range $recentActivities = ActivityLogger::betweenDates($startDate, $endDate); // Get activities by log name $securityLogs = ActivityLogger::inLog('security'); // Complex queries $activities = ActivityLog::where('log_name', 'user-management') ->whereNotNull('causer_id') ->with(['subject', 'causer']) ->latest() ->paginate(20);
Working with Activity Properties
// Get resolved changes with human-readable names $activity = ActivityLog::latest()->first(); $changesSummary = $activity->getChangesSummary(); foreach ($changesSummary as $change) { echo "{$change['field']}: '{$change['old_value']}' โ '{$change['new_value']}'\n"; } // Access raw properties $properties = $activity->properties; $ipAddress = $activity->getProperty('ip_address'); // Check for specific changes if ($activity->hasChanges('email')) { $oldEmail = $activity->getOldValue('email'); $newEmail = $activity->getNewValue('email'); }
Conditional Logging
// Disable logging temporarily User::withoutActivityLogging(function () { User::create($userData); }); // Disable logging for specific instance $user->disableLogging(); $user->update($data); $user->enableLogging(); // Skip empty logs $user->skipEmptyLogs()->update($data);
Statistics and Analytics
use Litepie\Logs\Helpers\ActivityLogger; // Get general statistics $stats = ActivityLogger::getStatistics(); // Get activity trends $trends = ActivityLogger::getTrends(30); // Last 30 days // Get top active users $topUsers = ActivityLogger::getTopUsers(10); // Get activity by event type $eventStats = ActivityLogger::getEventStatistics();
Console Commands
The package includes several useful Artisan commands:
Clean Old Activity Logs
# Clean logs older than configured retention period php artisan logs:clean # Clean logs older than specific number of days php artisan logs:clean --days=90 # Dry run to see what would be deleted php artisan logs:clean --dry-run
Export Activity Logs
# Export to CSV php artisan logs:export --format=csv --output=/path/to/export.csv # Export with filters php artisan logs:export --format=json --log-name=security --start-date=2024-01-01 # Export for specific user php artisan logs:export --causer-id=123 --format=pdf
Activity Statistics
# Show activity statistics php artisan logs:stats # Show detailed statistics php artisan logs:stats --detailed # Show statistics for specific period php artisan logs:stats --days=30
API Endpoints
Enable API routes in configuration and access logs via RESTful endpoints:
// config/logs.php 'enable_api_routes' => true,
Available endpoints:
GET /api/activity-logs
- List activitiesGET /api/activity-logs/{id}
- Get specific activityGET /api/activity-logs/stats
- Get statisticsGET /api/activity-logs/export
- Export activities
Performance Optimization
Database Partitioning
For high-volume applications, enable monthly partitioning:
// config/logs.php 'enable_partitioning' => true,
This creates monthly partitions automatically for better query performance.
Queue Processing
Enable asynchronous processing for better performance:
// config/logs.php 'queue_logs' => true, 'queue_connection' => 'redis',
Caching
Enable statistics caching:
// config/logs.php 'performance' => [ 'cache_statistics' => true, 'cache_duration' => 3600, // 1 hour ],
Privacy and Security
Data Protection
// config/logs.php 'privacy' => [ 'anonymize_ip' => true, 'exclude_fields' => ['password', 'ssn', 'credit_card'], 'hash_sensitive_data' => true, ],
Field Exclusion
class User extends Model { use LogsActivity; // Exclude sensitive fields from logging protected $logExcept = ['password', 'remember_token']; // Or specify only fields to include protected $logOnly = ['name', 'email', 'status']; }
Testing
composer test
Documentation
- ๐ Usage Examples - Comprehensive examples and real-world implementations
- ๐ Changelog - What has changed recently
- ๐ค Contributing Guide - How to contribute to this project
- โ๏ธ License - MIT License details
Changelog
Please see docs/changelog.md for more information on what has changed recently.
Contributing
Please see docs/contributing.md for details on how to contribute to this project.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see docs/license.md for more information.
Support
- ๐ Examples & Tutorials - Learn with comprehensive examples
- ๐ Issues - Report bugs or request features
- ๐ฌ Discussions - Ask questions and share ideas
- ๐ง Email Support - Professional support available
What's Next?
- Advanced dashboard for activity visualization
- Real-time activity streaming
- Machine learning-powered anomaly detection
- Integration with popular monitoring tools
- Mobile app for activity monitoring
Made with โค๏ธ by the Litepie Team