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 Activitylog Laravel Package

spatie/laravel-activitylog

Log user and model activity in Laravel with a simple API. Automatically record Eloquent events, track subjects and causers, attach custom properties, and query everything via the Activity model. Stores logs in the activity_log table.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Audit & Compliance: Fits seamlessly into Laravel’s ecosystem for tracking user/model interactions, ideal for audit trails, regulatory compliance (e.g., GDPR, SOX), or debugging.
  • Event-Driven Logging: Leverages Laravel’s Eloquent events (e.g., saved, deleted) for automatic activity capture, reducing boilerplate.
  • Extensibility: Supports custom properties, log names, and model-specific configurations via fluent methods (performedOn(), causedBy(), etc.).
  • Separation of Concerns: Isolates logging logic from business logic, adhering to clean architecture principles.

Integration Feasibility

  • Laravel Native: Zero configuration required beyond migration/publish steps; integrates with Laravel’s auth system, Eloquent, and service container.
  • Database Agnostic: Works with any supported Laravel database (MySQL, PostgreSQL, SQLite) and allows custom table/connection via model overrides.
  • Event System Compatibility: Hooks into Laravel’s event system for model-level logging (e.g., Model::saved() triggers automatic logs).
  • Middleware/Observer Support: Can be combined with Laravel’s middleware or observers for granular control over logging triggers.

Technical Risk

  • Performance Overhead:
    • Risk: High-frequency logging (e.g., per-request) may impact DB performance.
    • Mitigation: Use clean_after_days to purge old logs; disable logging for non-critical actions (activity()->disableLogging()).
  • Schema Assumptions:
    • Risk: Default migration assumes integer IDs; UUIDs or polymorphic relationships require customization.
    • Mitigation: Override the Activity model or modify the migration.
  • Soft Deletes:
    • Risk: Logged subjects (models) may be soft-deleted, leading to orphaned logs.
    • Mitigation: Configure include_soft_deleted_subjects or handle deletions via model observers.
  • Versioning:
    • Risk: Major version upgrades may require schema migrations (e.g., v4→v5).
    • Mitigation: Review UPGRADING.md and test thoroughly in staging.

Key Questions

  1. Scope of Logging:
    • Which models/actions require logging? (e.g., all CRUD, only sensitive operations)
    • Should logging be enabled/disabled per environment (e.g., ACTIVITYLOG_ENABLED=false in staging)?
  2. Data Retention:
    • What’s the acceptable clean_after_days value? (Default: 365 days)
    • Are there legal requirements for log retention periods?
  3. Performance:
    • Will logging impact critical paths? (e.g., API endpoints with high QPS)
    • Should logging be async (e.g., via queues) for high-volume systems?
  4. Customization:
    • Are custom properties/actions needed (e.g., logging IP addresses, metadata)?
    • Should the Activity model be extended for additional fields (e.g., log_type)?
  5. Monitoring:
    • How will logs be queried/analyzed? (e.g., direct DB queries, custom API endpoints, third-party tools like Laravel Scout or ELK).
    • Are there alerts for suspicious activity (e.g., mass deletions)?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Core: Works natively with Laravel 8+/9+/10+; no framework-specific conflicts.
    • Auth: Integrates with Laravel’s auth system (e.g., causedBy(auth()->user())).
    • Eloquent: Automatically logs model events (e.g., created, updated, deleted).
    • Service Container: Bind custom loggers or actions via the container.
  • Database:
    • Supports all Laravel-supported databases; custom table/connection via model override.
    • Schema is simple (1 table: activity_log) but extensible.
  • Testing:
    • Compatible with Laravel’s testing tools (e.g., mock Activity::all() in unit tests).
    • Includes built-in test suite for package validation.

Migration Path

  1. Installation:
    composer require spatie/laravel-activitylog
    php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-migrations"
    php artisan migrate
    
    • Note: Adjust subject_id/causer_id types if using UUIDs or non-integer IDs.
  2. Configuration:
    • Publish config (optional):
      php artisan vendor:publish --provider="Spatie\Activitylog\ActivitylogServiceProvider" --tag="activitylog-config"
      
    • Customize config/activitylog.php (e.g., clean_after_days, default_except_attributes).
  3. Model Setup:
    • Register models for automatic logging via traits or observers:
      use Spatie\Activitylog\Traits\LogsActivity;
      
      class User extends Model {
          use LogsActivity;
      }
      
    • Or manually log activities:
      activity()->performedOn($post)->causedBy($user)->log('Published post');
      
  4. Testing:
    • Validate logs in feature tests:
      $this->assertCount(1, Activity::all());
      $this->assertEquals('Published post', Activity::first()->description);
      

Compatibility

  • Laravel Versions: Tested on Laravel 8+; check composer.json for supported versions.
  • PHP Versions: Requires PHP 8.0+ (as of v5.x).
  • Dependencies: No major conflicts with popular Laravel packages (e.g., Laravel Scout, Nova, Sanctum).
  • Customization:
    • Override default behavior via config (e.g., actions, activity_model).
    • Extend the Activity model for additional fields or logic.

Sequencing

  1. Phase 1: Core Integration (1–2 sprints):
    • Install, configure, and test basic logging for 1–2 critical models.
    • Validate automatic event logging (e.g., created, deleted).
  2. Phase 2: Customization (1 sprint):
    • Adjust config (e.g., clean_after_days, default_except_attributes).
    • Implement custom properties/actions if needed.
  3. Phase 3: Monitoring & Optimization (Ongoing):
    • Set up log queries/APIs for stakeholders.
    • Optimize performance (e.g., async logging, query scopes).
    • Implement alerts for anomalies (e.g., mass deletions).

Operational Impact

Maintenance

  • Package Updates:
    • Minor updates: Low risk (follow Spatie’s changelog).
    • Major updates: Review UPGRADING.md; test in staging (e.g., v4→v5 may require schema changes).
  • Schema Management:
    • Monitor activity_log table growth; adjust clean_after_days as needed.
    • Consider partitioning large tables for performance.
  • Dependency Risks:
    • Laravel core updates may require package compatibility checks.
    • Monitor for breaking changes in Spatie’s dependencies (e.g., laravel-model-activity).

Support

  • Troubleshooting:
    • Common issues: Logging not triggering (check model observers/traits), permission errors (ensure causer is resolvable).
    • Debugging: Use Activity::all() or query scopes (e.g., Activity::where('description', 'like', '%published%')).
  • Community:
    • Active GitHub issues/PRs; responsive maintainers (Spatie).
    • Documentation is comprehensive (e.g., event logging).
  • Custom Solutions:
    • Extend the Activity model or create custom actions for edge cases (e.g., logging API requests).

Scaling

  • Performance:
    • High-Volume Systems: Use async logging (e.g., queue Spatie\Activitylog\Events\Logging events).
    • Query Optimization: Add indexes to activity_log (e.g., causer_id, created_at).
    • Read Replicas: Offload log queries to replicas if Activity::all() is frequent.
  • Storage:
    • Archive old logs to cold storage (e.g., S3) if retention exceeds DB limits.
    • Consider read models (e.g., Elasticsearch) for complex queries.
  • Distributed Systems:
    • In multi-server setups, ensure all instances write to the same DB or use a centralized logging service.

Failure Modes

Failure Scenario Impact Mitigation
Database downtime Logs lost during outages. Use transactions or queue failed logs for retry.
activity_log table corruption Inconsistent or missing logs. Regular backups; monitor DB health.
Auth system failures causer field populated incorrectly. Fallback to manual logging or IP-based attribution.
High logging volume DB performance degradation. Implement rate limiting (e.g., `clean_after
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport