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

Yammi Audit Log Laravel Laravel Package

romalytar/yammi-audit-log-laravel

Audit log for Laravel that tracks full provenance of every change: actor, origin, and correlation ID across queues and services. Built for distributed, queue-heavy apps to trace who triggered a write and through what execution chain.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require romalytar/yammi-audit-log-laravel
    php artisan migrate
    

    This creates the audit_log table and optional tables for advanced features.

  2. First Use Case:

    // No model setup required. Changes are automatically audited:
    User::first()->update(['name' => 'Test']);
    

    The change is recorded with actor (who executed it), origin (who initiated it), and correlation ID (ties the chain together).

  3. Enable Dashboard (Optional):

    php artisan audit-log:ui enable
    

    Access the dashboard at /audit-log to view changes.


Implementation Patterns

Core Workflow: Capturing Changes

  • Zero-Model Setup: No traits, interfaces, or observers required. All Eloquent model changes (created, updated, deleted, restored) are automatically audited.
  • Manual Recording for Non-Eloquent Changes:
    // For raw SQL or Query Builder updates:
    AuditLog::record($model, 'updated', ['field' => 'new_value']);
    

Provenance Chain Tracking

  • Actor/Origin Resolution: Automatically resolves the actor (e.g., ChargeOrderJob) and origin (e.g., John Doe) for every change, even across queues.
    // Example: A user triggers a job that updates a model:
    User::find(1)->dispatch(new ProcessPaymentJob());
    // Audit log will show:
    // - Actor: ProcessPaymentJob
    // - Origin: John Doe (user who triggered the job)
    

Advanced Features Integration

  1. Time Machine:

    $pastState = AuditLog::timeMachine()->getState(User::class, 1, '2023-01-01');
    

    Reconstructs a model's state at a past timestamp.

  2. Anomaly Detection:

    AuditLog::anomaly()->detect('status_changed_to_cancelled', 5); // Alert if >5 cancellations in 1 hour
    
  3. GDPR Reports:

    $userData = AuditLog::gdpr()->getSubjectData(User::class, 1);
    
  4. Multi-Tenancy:

    AuditLog::setTenant('tenant_id_123'); // Scope logs to a tenant
    

Querying Audit Logs

  • Basic Query:
    $logs = AuditLog::query()
        ->model(User::class)
        ->field('status')
        ->value('active')
        ->get();
    
  • Correlation Chain:
    $chain = AuditLog::query()
        ->correlation('550e8400-e29b-41d4-a716-446655440000')
        ->withChain()
        ->get();
    

Performance Optimization

  • Async Writes:

    AUDIT_LOG_WRITE_ASYNC=true
    

    Offloads audit log writes to a queue.

  • Sampling High-Churn Models:

    AuditLog::ignoreModel(User::class); // Skip auditing for this model
    AuditLog::sampleModel(Order::class, 0.1); // Audit 10% of changes
    

Gotchas and Tips

Pitfalls

  1. Non-Eloquent Changes:

    • Issue: Changes via raw SQL or Query Builder are not automatically audited.
    • Fix: Manually record them:
      AuditLog::record($model, 'updated', ['field' => 'value']);
      
  2. Correlation ID Leaks:

    • Issue: Correlation IDs may expose internal request IDs in logs.
    • Fix: Redact sensitive fields in config/audit-log.php:
      'redact' => ['correlation_id', 'token', 'api_key'],
      
  3. Dashboard Access:

    • Issue: The dashboard is disabled by default for security.
    • Fix: Enable it explicitly:
      php artisan audit-log:ui enable
      
  4. Retention Policy:

    • Issue: Default retention is 180 days. Longer retention may bloat storage.
    • Fix: Adjust in config/audit-log.php:
      'retention' => ['days' => 365],
      
  5. Multi-Tenancy Conflicts:

    • Issue: Tenant-scoped logs may interfere if not properly isolated.
    • Fix: Always set the tenant context:
      AuditLog::setTenant('tenant_id');
      

Debugging Tips

  1. Verify Capture:

    AuditLog::debug()->enable(); // Logs capture events to Laravel logs
    
  2. Check Provenance Chain:

    • If the origin is missing, ensure the job/user context is preserved across queues (e.g., via AuditLog::setOrigin() in jobs).
  3. Slow Queries:

    • Use the indexed changed_keys table for field searches:
      AuditLog::query()->field('status')->value('active')->get();
      

Extension Points

  1. Custom Actors/Origins:

    • Extend the provider chain in config/audit-log.php:
      'actors' => [
          \App\Providers\CustomActorProvider::class,
      ],
      
  2. Add Custom Fields to Logs:

    AuditLog::extend(function ($log) {
        $log->customField = 'value';
    });
    
  3. Override Default Diff:

    • Disable default diff and provide a custom one:
      AuditLog::diff(function ($old, $new) {
          return ['custom_diff' => $old->diffAssoc($new)];
      });
      
  4. Integrate with SIEM:

    • Stream logs to a SIEM via the AuditLog::stream() event listener:
      AuditLog::stream(function ($log) {
          // Send to Splunk/Datadog
      });
      

Configuration Quirks

  1. Async Writes:

    • If using AUDIT_LOG_WRITE_ASYNC=true, ensure the queue worker processes audit logs promptly to avoid gaps.
  2. UI Middleware:

    • The dashboard uses Laravel's web middleware by default. Customize in config/audit-log.php:
      'ui' => [
          'middleware' => ['web', 'auth'],
      ],
      
  3. Database Connection:

    • Move audit logs to a dedicated connection:
      'write' => [
          'connection' => 'audit_log_db',
      ],
      
  4. Event Versioning:

    • Enable schema contracts for backward compatibility:
      'governance' => [
          'event_version' => true,
      ],
      

Pro Tips

  1. Impersonation Handling:

    • Automatically log impersonation context:
      AuditLog::setImpersonator('admin_id');
      
  2. Bulk Operations:

    • Disable auditing for bulk operations to improve performance:
      AuditLog::ignore(function () {
          User::where('active', false)->update(['deleted_at' => now()]);
      });
      
  3. Alerts for Critical Changes:

    • Set up anomaly detection rules:
      AuditLog::anomaly()->rule('critical_change', function ($log) {
          return $log->field('status') === 'deleted' && $log->model === User::class;
      })->threshold(1)->window('1 hour')->alertVia('slack');
      
  4. GDPR Right to Erasure:

    • Generate compliance reports:
      $report = AuditLog::gdpr()->generateReport(User::class, 1);
      
  5. Cross-Model Traces:

    • Use correlation IDs to trace workflows across models:
      $correlationId = AuditLog::getCorrelationId();
      AuditLog::query()->correlation($correlationId)->get();
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky