Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Activity Logger Laravel Package

syamsoul/laravel-activity-logger

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require syamsoul/laravel-activity-logger
    php artisan vendor:publish --provider="SoulDoit\ActivityLogger\ActivityLoggerServiceProvider"
    

    Publish the config file to config/activity-logger.php.

  2. Basic Usage: Inject the Logger class into any class (e.g., Command, Controller, Middleware) via constructor or method parameter.

    use SoulDoit\ActivityLogger\Logger;
    
    public function __construct(protected Logger $logger) {}
    
  3. First Log Entry:

    $this->logger->log('Order processing started', [
        'order_id' => 123,
        'user_id' => 456,
        'status' => 'pending'
    ]);
    

Key Configurations

  • Check config/activity-logger.php for:
    • log_channel: Default logging channel (e.g., activity_log).
    • log_table: Database table name (default: activity_logs).
    • log_model: Custom model path (if extending default behavior).

Implementation Patterns

Logging Workflows

1. Command Logging

protected $signature = 'user:export {user_id}';
protected $description = 'Export user data';

public function handle(Logger $logger) {
    $logger->log('Export command initiated', ['user_id' => $this->argument('user_id')]);

    // Business logic...

    $logger->log('Export completed successfully', ['file_path' => '/path/to/file.csv']);
}

2. Controller/Route Logging

public function update(Request $request, $id) {
    $this->logger->log('User update request', [
        'user_id' => $id,
        'changes' => $request->all()
    ]);

    // Update logic...

    return response()->json(['status' => 'updated']);
}

3. Middleware Logging

public function handle($request, Closure $next) {
    $this->logger->log('API request received', [
        'method' => $request->method(),
        'path' => $request->path(),
        'ip' => $request->ip()
    ]);

    return $next($request);
}

Integration Tips

  • Database Table Structure: The package creates a table with columns like id, activity, details, ip_address, user_id, created_at. Customize via migrations if needed.

  • Log Channels: Extend logging to other channels (e.g., Slack, Datadog) by configuring log_channel in the config file.

  • Event-Based Logging: Bind events to log activities automatically:

    event(new OrderPlaced($order));
    // Log via event observer or listener
    
  • Batch Processing: Use logBatch() for bulk operations:

    $this->logger->logBatch([
        ['activity' => 'Processed record 1', 'details' => [...]],
        ['activity' => 'Processed record 2', 'details' => [...]]
    ]);
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Avoid logging in tight loops or high-frequency operations. Use logBatch() for bulk inserts.
    • Example: Log once per batch instead of per item.
  2. Missing User Context:

    • If user_id is not set in logs, ensure middleware (e.g., Authenticate) runs before logging. Use auth()->user()->id explicitly if needed.
  3. Config Overrides:

    • Forgetting to publish the config file (php artisan vendor:publish) will use default values, which may not align with your needs.
  4. Database Locking:

    • Heavy logging during peak times may cause database contention. Consider async logging (e.g., queues) for critical paths.

Debugging

  • Check Logs: Verify entries in the activity_logs table or configured channel (e.g., storage/logs/laravel.log).

    SELECT * FROM activity_logs ORDER BY created_at DESC LIMIT 10;
    
  • Logger Not Injecting: Ensure the Logger class is properly bound in the service container. If using Laravel 8+, autowiring should handle this automatically.

  • Custom Model Issues: If extending the default model, ensure the log_model path in config points to the correct namespace/class.

Extension Points

  1. Custom Log Model: Extend the default ActivityLog model to add fields or methods:

    namespace App\Models;
    use SoulDoit\ActivityLogger\Models\ActivityLog as BaseActivityLog;
    
    class ActivityLog extends BaseActivityLog {
        protected $casts = [
            'details' => 'array',
        ];
    }
    

    Update log_model in config:

    'log_model' => App\Models\ActivityLog::class,
    
  2. Log Filters: Add filters to exclude sensitive data:

    $this->logger->log('User login', [
        'password' => '*****', // Will be logged as-is unless filtered
        'email' => $request->email
    ]);
    

    Override the ActivityLog model to sanitize details before saving.

  3. Async Logging: Use Laravel queues to offload logging:

    $this->logger->log('Async task started');
    dispatch(new LogActivityJob('Async task completed', ['data' => $data]));
    
  4. Activity Triggers: Create a trait to auto-log method calls:

    trait LogsActivity {
        protected $logger;
    
        public function __construct(Logger $logger) {
            $this->logger = $logger;
        }
    
        public function logMethodCall(string $method, array $params) {
            $this->logger->log("Method {$method} called", $params);
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope