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

spatie/laravel-notification-log

Logs all notifications sent by your Laravel app, storing them as NotificationLogItems so you can query what was sent to a user, display notification history, and make sending decisions (e.g., avoid duplicates) via helpers like wasSentTo() and inThePastMinutes().

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven Alignment: The package leverages Laravel’s built-in notification system, which is already event-driven (via NotificationSent events). This aligns well with modern Laravel architectures that use events, queues, or observers for side effects.
  • Separation of Concerns: Logs notifications without modifying core notification logic, adhering to the principle of least surprise. Ideal for systems requiring audit trails, compliance, or debugging.
  • Extensibility: Supports custom log channels (e.g., databases, external APIs) via Laravel’s logging configuration, making it adaptable to diverse storage needs.
  • Lightweight: Minimal overhead (~1 event listener + log entry per notification), suitable for high-throughput systems if configured efficiently (e.g., async logging).

Integration Feasibility

  • Laravel Native: Zero friction for Laravel apps (v8+). Requires only composer require and minimal configuration.
  • Database Dependency: Defaults to storing logs in a notification_logs table, requiring a migration. Compatible with Eloquent models, but may need schema adjustments for complex use cases (e.g., soft deletes, archiving).
  • Notification Customization: Works with all Laravel notifications (mail, Slack, SMS, etc.), but custom notification classes must ensure toMail, toArray, etc., are properly defined for accurate logging.
  • Queue Integration: Logs are written synchronously by default. For async logging, requires pairing with Laravel queues or a custom channel.

Technical Risk

  • Performance: Synchronous logging could impact notification throughput in high-volume systems. Mitigation: Use async logging (e.g., queue listeners) or a dedicated log channel.
  • Data Bloat: Unfiltered logging may fill storage with noise. Risk: Mitigate via query scopes (e.g., recent(), failed()) or TTL policies.
  • Schema Rigidity: Default table structure may not fit legacy systems. Risk: Customize via NotificationLog model or create a separate table.
  • Testing Overhead: Requires testing notification flows end-to-end, including logging. Risk: Use feature tests with NotificationFake or mock the logger.

Key Questions

  1. Storage Backend: Will logs be stored in the primary DB, or a dedicated service (e.g., Elasticsearch, S3)? Does the team have experience with custom log channels?
  2. Retention Policy: How long should logs be retained? Are there compliance requirements (e.g., GDPR) affecting archival?
  3. Async Logging: Is synchronous logging acceptable, or must logs be written asynchronously to avoid blocking notification delivery?
  4. Notification Volume: What’s the expected scale (e.g., 10k/day vs. 1M/day)? Will indexing or querying logs be a bottleneck?
  5. Custom Fields: Are additional metadata fields (e.g., user_id, campaign_id) needed beyond the default log structure?
  6. Monitoring: Should log entries trigger alerts (e.g., failed notifications)? If so, how will this integrate with existing monitoring (e.g., Sentry, Datadog)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Perfect fit for Laravel apps using notifications (v8+). Compatible with:
    • Queues: queue:work for async notifications.
    • Horizon: For monitoring async notification jobs.
    • Scout/Algolia: If notifications are searchable, logs can be indexed similarly.
    • Testing: Works with Laravel’s NotificationFake for unit/feature tests.
  • Database: Optimized for PostgreSQL/MySQL. For other DBs (e.g., SQLite), ensure timestamps and softDeletes are compatible.
  • Monoliths/Microservices: Best for monoliths. In microservices, consider exposing logs via an API or event bus (e.g., Kafka) if notifications span services.

Migration Path

  1. Assessment Phase:
    • Audit existing notification classes for toArray()/toMail() methods.
    • Review current logging strategy (e.g., does the team already use Log::channel()?).
  2. Setup:
    composer require spatie/laravel-notification-log
    php artisan vendor:publish --provider="Spatie\NotificationLog\NotificationLogServiceProvider"
    php artisan migrate
    
  3. Configuration:
    • Customize config/notification-log.php (e.g., log channels, table name).
    • Extend NotificationLog model if additional fields are needed.
  4. Testing:
    • Write feature tests for critical notification flows (e.g., UserSentPasswordResetNotification).
    • Verify logs appear in the expected table/channel.
  5. Deployment:
    • Roll out in a staging environment first, monitoring log table growth and query performance.

Compatibility

  • Laravel Versions: Officially supports v8+. For v7, check for breaking changes in the changelog.
  • PHP Versions: Requires PHP 8.0+. Test for compatibility with older versions if needed.
  • Notification Types: Works with all Laravel notifications (including custom ones), but ensure via() and to* methods are implemented.
  • Third-Party Notifications: May need adjustments for non-Laravel notifications (e.g., via Notification::route() or custom event listeners).

Sequencing

  1. Phase 1 (Core Integration):
    • Install and configure the package.
    • Log a subset of high-priority notifications (e.g., password resets, payment receipts).
  2. Phase 2 (Optimization):
    • Implement async logging if needed (e.g., queue a LogNotification job).
    • Add custom fields or indexes for common queries.
  3. Phase 3 (Monitoring):
    • Set up alerts for failed notifications or log volume spikes.
    • Integrate with existing dashboards (e.g., Grafana for log count trends).
  4. Phase 4 (Scaling):
    • Archive old logs (e.g., via Laravel Housekeeping or a cron job).
    • Offload to a dedicated service if log volume becomes prohibitive.

Operational Impact

Maintenance

  • Package Updates: Low maintenance—Spatie packages are battle-tested. Monitor for Laravel version deprecations (e.g., if Laravel drops PHP 8.0 support).
  • Schema Changes: Minimal; only update if extending the NotificationLog model or table.
  • Dependencies: No external services by default, but custom channels may introduce complexity (e.g., S3 logging requires AWS credentials management).

Support

  • Debugging: Logs provide a clear audit trail for notification failures (e.g., "Why did this email not send?"). Useful for:
    • User support (e.g., "We sent a reset link at 2 PM").
    • Compliance audits (e.g., "All users received the GDPR notice").
  • Troubleshooting: Failed notifications can be queried via:
    $failedLogs = NotificationLog::where('exception', '!=', null)->latest()->get();
    
  • Documentation: Spatie’s docs are clear, but internal docs should cover:
    • How to query logs (e.g., NotificationLog::forUser($user)).
    • Alert thresholds (e.g., "Notify ops if >100 failed logs/hour").

Scaling

  • Database Load:
    • Reads: Add indexes for frequent queries (e.g., user_id, notifiable_type).
    • Writes: For high volume, use a queue to batch log writes or switch to a dedicated log service (e.g., Elasticsearch).
  • Archiving: Implement a cron job to archive logs older than 6 months to a cold storage layer (e.g., S3).
  • Replication: If using a read replica, ensure log queries use the replica to avoid write contention.

Failure Modes

Failure Scenario Impact Mitigation
Database downtime Logs lost during outage. Use a queue + retry logic for logging.
Unhandled notification exceptions Logs may not capture full context. Wrap Notification::send() in a try-catch and log exceptions manually.
Log table bloat Slow queries, storage costs. Set TTL policies or archive old logs.
Custom channel failures (e.g., S3) Logs not persisted. Implement fallback to DB logging or alert on channel failures.
Laravel queue failures Async logs delayed/failed. Monitor queue backlogs; implement dead-letter queues for failed log jobs.

Ramp-Up

  • Developer Onboarding:
    • 10 mins: Install and log a simple notification.
    • 30 mins: Query logs for debugging (e.g., "Show me all failed emails to user X").
    • 1 hour: Customize the log structure or add a custom channel.
  • Team Training:
    • Product Managers: Teach them to query logs for user support (e.g., "When was this feature announcement sent?").
    • Engineers: Train on extending the package (e.g., adding sent_at to a custom field).
  • **Document
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