PHP code example of litepie / logs

1. Go to this page and download the library: Download litepie/logs library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

litepie / logs example snippets


use Litepie\Logs\Traits\LogsActivity;

class User extends Model
{
    use LogsActivity;
    
    protected $fillable = ['name', 'email'];
}

$user = User::create(['name' => 'John', 'email' => '[email protected]']);
// ✅ Logged: "User created"

$user->update(['name' => 'Jane']);
// ✅ Logged: "User updated" with change details

$user->delete();
// ✅ Logged: "User deleted"

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...
];



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';
}

$user = User::create(['name' => 'John Doe', 'email' => '[email protected]']);
// Automatically logs: "User created"

$user->update(['name' => 'Jane Doe']);
// Automatically logs: "User updated" with changes

$user->delete();
// Automatically logs: "User deleted"

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);
    }
}

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');

$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();

// config/logs.php
'enable_api_routes' => true,

// config/logs.php
'enable_partitioning' => true,

// config/logs.php
'queue_logs' => true,
'queue_connection' => 'redis',

// 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 
bash
php artisan vendor:publish --provider="Litepie\Logs\LogsServiceProvider" --tag="config"
php artisan migrate
bash
# 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
bash
# 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