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

cetiia/laravel-activity-log

Laravel package that automatically records application activity to a logs table after migration and provides an activity-log route to view entries. Includes publishable migrations and optional views; access to the route can be protected via a Gate in AuthServiceProvider.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven Logging: The package leverages Laravel’s built-in event system (Illuminate\Queue\Events\JobProcessed, eloquent.*, etc.) to log activities, aligning well with Laravel’s native architecture. This reduces boilerplate for tracking model changes, API calls, or system events.
  • Observer-Based: Uses Eloquent observers to log model events (created, updated, deleted), which is a clean separation of concerns but requires explicit observer registration.
  • Middleware Support: Can be extended via middleware (e.g., logging HTTP requests/responses), though this is not natively supported and would require customization.
  • Database Agnostic: Works with any database Laravel supports, but schema design (e.g., activity_logs table) must be manually managed or scaffolded.
  • Limited Real-Time Features: No built-in WebSocket or real-time notifications; logs are stored in the database for later retrieval.

Integration Feasibility

  • Low-Coupling: Minimal impact on existing codebase if using event-based logging. Observers require explicit binding to models.
  • Customization Points:
    • Log format (via ActivityLog facade or service provider bindings).
    • Logged events (extendable via events or observers).
    • Storage (database only; no support for external systems like Elasticsearch or S3).
  • Testing Overhead: Requires unit/integration tests for observer/event logic, especially if customizing log behavior.

Technical Risk

  • Schema Management: No migrations included; users must define the activity_logs table (risk of misconfiguration).
  • Performance: Heavy logging (e.g., per-model observer on high-traffic tables) could impact performance. No built-in rate limiting or batching.
  • Dependency Bloat: Adds a small but unnecessary dependency if logging needs are minimal (e.g., only API calls).
  • Limited Documentation: Lack of stars/docs suggests potential gaps in edge-case handling (e.g., soft deletes, polymorphic relationships).
  • No Built-in API: Logs are database-only; querying requires raw SQL or Eloquent queries (no GraphQL/REST endpoints).

Key Questions

  1. Use Case Clarity:
    • Is logging needed for all model changes, or only specific ones (e.g., sensitive data like users)?
    • Are logs required for non-model events (e.g., cron jobs, queue failures)?
  2. Scalability:
    • How will log volume grow? Is database indexing planned for the activity_logs table?
    • Will logs be archived/pruned? (No built-in TTL or cleanup.)
  3. Alternatives:
    • Could Laravel’s native Illuminate\Foundation\Events + a custom table suffice?
    • Is a dedicated package like spatie/laravel-activitylog (more mature) worth the switch?
  4. Extensibility:
    • Will custom log fields (e.g., IP addresses, user agents) be needed? How will they be stored?
    • Are there plans to add real-time features (e.g., notifications) later?
  5. Team Skills:
    • Is the team comfortable with Eloquent observers/events, or would a simpler approach (e.g., middleware) be preferable?

Integration Approach

Stack Fit

  • Laravel Native: Perfect fit for Laravel apps using Eloquent, events, or middleware. Avoids reinventing the wheel for common logging needs.
  • PHP Version: Compatible with Laravel 8+ (PHP 8.0+). No major version conflicts expected.
  • Database: Works with MySQL, PostgreSQL, SQLite, etc., but schema must be manually set up.
  • Queue Support: Logs can be queued (if using sync:handle or queues), but this requires explicit configuration.

Migration Path

  1. Schema Setup:
    • Create activity_logs table (or use a seed/migration template from the package’s config).
    • Example fields: id, user_id, event, old_values, new_values, created_at.
  2. Observer Registration:
    • Bind observers to models in AppServiceProvider@boot():
      User::observe(ActivityLogObserver::class);
      
    • Or use events (e.g., Creating, Updating) with a global listener.
  3. Configuration:
    • Publish config (php artisan vendor:publish --tag="activity-log-config") to customize logged fields, excluded models, or event mappings.
  4. Testing:
    • Verify logs appear for critical actions (e.g., User::create(), Post::update()).
    • Test edge cases: soft deletes, mass updates, or events without observers.

Compatibility

  • Laravel Versions: Tested on Laravel 8+; may need adjustments for older versions (e.g., PHP 7.4).
  • Custom Events: Supports custom events via ActivityLog::logEvent(), but requires manual wiring.
  • Third-Party Packages: No known conflicts with popular packages (e.g., Laravel Nova, Sanctum), but test with:
    • Authentication (e.g., auth()->user() in observers).
    • API tools (e.g., logging API requests via middleware).
  • Legacy Code: Observers may conflict with existing model hooks (e.g., boot() methods). Use method priority checks if needed.

Sequencing

  1. Phase 1: Core Logging
    • Implement for 2–3 critical models (e.g., User, Order).
    • Validate log format and query performance.
  2. Phase 2: Extensions
    • Add middleware for HTTP logging (custom code).
    • Extend with custom events or fields.
  3. Phase 3: Optimization
    • Index activity_logs table for large datasets.
    • Implement log pruning (e.g., via Laravel schedules).
  4. Phase 4: Monitoring
    • Add alerts for log failures (e.g., database errors).
    • Integrate with error tracking (e.g., Sentry) if logs are critical.

Operational Impact

Maintenance

  • Schema Updates: Manual changes required for new fields or indexes. Use migrations to version-control schema.
  • Observer Management:
    • Remove observers when models are deprecated to avoid orphaned logs.
    • Document which models use logging to aid future maintenance.
  • Configuration Drift: Publish config early to avoid hardcoding values in multiple places.
  • Dependency Updates: Monitor for Laravel/PHP version compatibility (MIT license allows forks if needed).

Support

  • Debugging:
    • Logs may obscure errors if observers fail silently (e.g., database connection issues).
    • Add error handling in observers (e.g., try-catch blocks).
  • Query Complexity:
    • Complex log queries (e.g., "show all changes to a user’s address") may require raw SQL or Eloquent scopes.
    • Consider adding a LogQueryBuilder facade for reusable queries.
  • User Access:
    • Logs may contain sensitive data (e.g., passwords in old_values). Restrict access via Laravel gates/policies.

Scaling

  • Database Load:
    • High-frequency logging (e.g., per-request) can bloat the database. Monitor activity_logs table growth.
    • Solutions:
      • Archive old logs to a separate table/database.
      • Use Laravel’s queue:work to batch log writes.
  • Performance:
    • Observers add overhead to model operations. Benchmark with/without logging in staging.
    • For high-traffic models, consider:
      • Logging only specific fields (e.g., email but not password).
      • Using a queue for non-critical logs.
  • Horizontal Scaling:
    • Logs are read-only after creation, so scaling reads is straightforward (e.g., read replicas).
    • Write scaling (e.g., multiple app servers) requires consistent observer/event handling.

Failure Modes

Failure Scenario Impact Mitigation
Database connection drops Lost logs during outages. Use queues + retries (queue:failed table).
Observer throws unhandled exception Breaks model operations. Wrap observer logic in try-catch.
Schema misconfiguration Logs unreadable or missing data. Use migrations + CI checks for schema.
High log volume Slow queries, storage bloat. Indexes, archiving, or sampling (log 10% of events).
Laravel event system disabled Logs not triggered. Fallback to middleware or direct DB inserts.

Ramp-Up

  • Onboarding Time: 1–2 days for basic setup; longer for customizations.
    • Developers: Need familiarity with Eloquent observers/events.
    • QA: Test edge cases (e.g., nested transactions, model deletions).
  • Documentation Gaps:
    • Fill gaps with internal docs for:
      • Observer/event wiring.
      • Log query examples.
      • Custom field extensions.
  • Training:
    • Demo how to:
      • Add logging to a new model.
      • Query logs for auditing.
      • Handle failures (e.g., queue:retry).
  • Tooling:
    • Add a
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