承接 litepie/logs 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

litepie/logs

Composer 安装命令:

composer require litepie/logs

包简介

A comprehensive activity log package for Laravel applications

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status PHPStan Analysis Total Downloads License

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.2, 8.3, or 8.4
  • Laravel: 10.x, 11.x, or 12.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 activities
  • GET /api/activity-logs/{id} - Get specific activity
  • GET /api/activity-logs/stats - Get statistics
  • GET /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

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 LICENSE for more information.

Support

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

🏢 About

This package is part of the Litepie ecosystem, developed by Renfos Technologies.

Organization Structure

  • Vendor: Litepie
  • Framework: Lavalite
  • Company: Renfos Technologies

Links & Resources

Built with ❤️ by Renfos Technologies

Empowering developers with robust Laravel solutions

litepie/logs 适用场景与选型建议

litepie/logs 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 36 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 08 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「log」 「Audit」 「laravel」 「activity」 「tracking」 「litepie」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 litepie/logs 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 litepie/logs 我们能提供哪些服务?
定制开发 / 二次开发

基于 litepie/logs 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 36
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 16
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-08-23