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.
- π 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
composer require litepie/logs
php artisan vendor:publish --provider="Litepie\Logs\LogsServiceProvider" --tag="config"
php artisan migrate
use Litepie\Logs\Traits\LogsActivity;
class User extends Model
{
use LogsActivity;
protected $fillable = ['name', 'email'];
}
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"
- PHP: 8.2, 8.3, or 8.4
- Laravel: 10.x, 11.x, or 12.x
- Database: MySQL 5.7+ (for partitioning features), PostgreSQL, SQLite
# 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
# 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+
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...
];
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"
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'"
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');
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');
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);
// 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');
}
// 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);
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();
The package includes several useful Artisan commands:
# 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 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
# 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
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
For high-volume applications, enable monthly partitioning:
// config/logs.php
'enable_partitioning' => true,
This creates monthly partitions automatically for better query performance.
Enable asynchronous processing for better performance:
// config/logs.php
'queue_logs' => true,
'queue_connection' => 'redis',
Enable statistics caching:
// config/logs.php
'performance' => [
'cache_statistics' => true,
'cache_duration' => 3600, // 1 hour
],
// config/logs.php
'privacy' => [
'anonymize_ip' => true,
'exclude_fields' => ['password', 'ssn', 'credit_card'],
'hash_sensitive_data' => true,
],
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'];
}
composer test
- π 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
Please see docs/changelog.md for more information on what has changed recently.
Please see docs/contributing.md for details on how to contribute to this project.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see LICENSE for more information.
- π Examples & Tutorials - Learn with comprehensive examples
- π Issues - Report bugs or request features
- π¬ Discussions - Ask questions and share ideas
- π§ Email Support - Professional support available
- Advanced dashboard for activity visualization
- Real-time activity streaming
- Machine learning-powered anomaly detection
- Integration with popular monitoring tools
- Mobile app for activity monitoring
This package is part of the Litepie ecosystem, developed by Renfos Technologies.
- Vendor: Litepie
- Framework: Lavalite
- Company: Renfos Technologies
- π Website: https://lavalite.org
- π Documentation: https://docs.lavalite.org
- πΌ Company: https://renfos.com
- π§ Support: support@lavalite.org
Built with β€οΈ by Renfos Technologies
Empowering developers with robust Laravel solutions