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

Filament Logger Laravel Package

mradder/filament-logger

Community-maintained Filament audit/activity logging built on spatie/laravel-activitylog. Includes a ready-made Activity resource with filters and diffs, CSV/JSON exports, dashboard widgets, and automatic logging for resources, models, auth, notifications, and custom events.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mradder/filament-logger
    php artisan filament-logger:install
    php artisan migrate
    
    • Publishes config (config/filament-logger.php) and Spatie ActivityLog migrations.
  2. Register the Activity Resource: Add to your PanelProvider:

    public function panel(Panel $panel): Panel {
        return $panel->resources([
            config('filament-logger.activity_resource'),
        ]);
    }
    
  3. First Use Case:

    • Immediately log all CRUD operations on your models via Filament resources.
    • Access the Activity Log in Filament’s sidebar to review changes (e.g., who created/updated/deleted records).

Implementation Patterns

Core Workflows

  1. Automatic Resource Logging:

    • Enable for any Filament resource by adding the HasActivityLog trait:
      use MrAdder\FilamentLogger\Concerns\HasActivityLog;
      
      class PostResource extends Resource {
          use HasActivityLog;
      }
      
    • Logs create/update/delete/restore/force-delete events with structured diffs (old/new values).
  2. Custom Model Logging:

    • Override getActivitylogOptions() in your model:
      public function getActivitylogOptions(): array {
          return [
              'only' => ['title', 'content'], // Log only these fields
              'ignore' => ['updated_at'],     // Exclude sensitive fields
          ];
      }
      
  3. Auth Event Tracking:

    • Logs logins, logouts, failed attempts, password resets, and 2FA events by default.
    • Filter guards in config:
      'access' => [
          'guards' => ['web'], // Only log auth events for the 'web' guard
      ]
      
  4. Custom Domain Events:

    • Dispatch events for business logic (e.g., OrderShipped):
      use MrAdder\FilamentLogger\Facades\FilamentLogger;
      
      event(new OrderShipped($order));
      FilamentLogger::logEvent('order.shipped', $order);
      
  5. Alerting:

    • Trigger alerts for high-risk actions (e.g., mass deletions):
      FilamentLogger::alert('user.deleted', [
          'user_id' => $user->id,
          'count' => $deletedCount,
      ]);
      
    • Configure alerts in config/filament-logger.php:
      'alerts' => [
          'channels' => ['mail', 'slack'],
          'rules' => [
              'user.deleted' => [
                  'cooldown' => 3600, // 1-hour cooldown
              ],
          ],
      ]
      

Integration Tips

  • Dashboard Widgets: Add to your PanelProvider:
    ->widgets([
        \MrAdder\FilamentLogger\Widgets\ActivityOverview::class,
        \MrAdder\FilamentLogger\Widgets\TopUsers::class,
    ])
    
  • Exports: Use the export menu in the Activity Log to download CSV/JSON for compliance.
  • Pruning: Schedule cleanup via Artisan:
    php artisan filament-logger:prune --days=30 --log-names=activity
    
    Add to app/Console/Kernel.php:
    protected function schedule(Schedule $schedule) {
        $schedule->command('filament-logger:prune')->daily();
    }
    

Gotchas and Tips

Pitfalls

  1. Authorization Strictness:

    • The Activity Log resource defaults to strict authorization. Ensure you register a policy:
      use MrAdder\FilamentLogger\Models\Activity;
      
      Gate::define('viewActivity', fn ($user) => $user->can('view-activity'));
      
    • Disable strict mode in config if needed:
      'strict_authorization' => false,
      
  2. Sensitive Data Exposure:

    • Passwords, tokens, and IPs are redacted by default, but historical logs may contain unsanitized data.
    • Use ignore in getActivitylogOptions() to exclude fields like api_token:
      'ignore' => ['api_token', 'password'],
      
  3. Performance:

    • Bulk operations (e.g., deleteMany) may generate many logs. Use ignore for non-critical fields:
      'ignore' => ['updated_at', 'deleted_at'],
      
    • Prune old logs regularly to avoid bloat.
  4. Custom Events:

    • Events must be stringifiable or castable to JSON. Avoid logging:
      • Database connections.
      • Circular references (e.g., User with orders relationship).
    • Use ->toArray() or json_encode() for complex data:
      FilamentLogger::logEvent('custom.event', $data->toArray());
      

Debugging

  1. Missing Logs:

    • Verify the resource/model has HasActivityLog or observer is registered.
    • Check config/filament-logger.php for log_models/log_resources settings.
    • Enable debug logging:
      'debug' => true,
      
  2. Alerts Not Triggering:

    • Confirm the event name matches the alert rule.
    • Check storage/logs/laravel.log for alert dispatch errors.
    • Test with a simple alert:
      FilamentLogger::alert('test.alert', ['message' => 'Hello']);
      
  3. Diff View Issues:

    • Large payloads (>1MB) may time out. Use ignore for verbose fields.
    • JSON formatting fails if data isn’t serializable. Use json_encode($data, JSON_THROW_ON_ERROR).

Extension Points

  1. Custom Log Labels: Override labels in config:

    'labels' => [
        'create' => 'Record Created',
        'update' => 'Record Updated',
    ],
    
  2. Additional Widgets: Extend the Widget class to add custom dashboards:

    class CustomActivityWidget extends Widget {
        protected static string $view = 'filament-logger::widgets.custom';
        // ...
    }
    
  3. Pre-Log Hooks: Intercept logs via the activity.logging event:

    Event::listen(\Spatie\Activitylog\Events\Logging::class, function ($event) {
        if ($event->logName === 'activity') {
            $event->cancel(); // Skip logging
        }
    });
    
  4. Retention Policies: Customize pruning in config:

    'pruning' => [
        'activity' => [
            'days' => 90,
            'dry_run' => false,
        ],
    ],
    

Pro Tips

  • Filter High-Risk Actions: Use the High Risk tab in the Activity Log to flag deletions/restores.
  • Anonymize IPs: Enable in config:
    'anonymize_ips' => true,
    
  • Localization: Translate labels via Filament’s language files (e.g., filament-logger::labels).
  • Testing: Mock logs in PHPUnit:
    $this->partialMock(Spatie\Activitylog\Activity::class, function ($mock) {
        $mock->shouldReceive('log')->once();
    });
    

```markdown
### Configuration Quirks
1. **Multi-Guard Apps**:
   - Auth events **default to all guards**. Explicitly whitelist guards in config:
     ```php
     'access' => [
         'guards' => ['web', 'api'], // Only log these guards
     ]
     ```
   - Events like `PasswordReset` **ignore guards** and always log.

2. **Notification Logging**:
   - Disabled by default for security. Enable with:
     ```php
     'notifications' => [
         'log_recipients' => true,
         'mask_recipients' => true, // Redact email addresses
     ]
     ```

3. **Legacy Filament 3**:
   - Uses **shims** for compatibility but may miss newer Filament 4/5 features.
   - Prefer Filament 4.3.1+ for full support.

4. **Database Indexes**:
   - The `activity_logs` table **auto-creates indexes** for `log_name`, `properties`, and `created_at`.
   - For large datasets, add custom indexes (e.g., `user_id`):
     ```php
     Schema::table('activity_logs', function (Blueprint $table) {
         $table->index('properties->user_id');
     });
     ```
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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