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

Auditor Bundle Laravel Package

damienharper/auditor-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require damienharper/auditor-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        DamienHarper\AuditorBundle\AuditorBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Create config/packages/dh_auditor.yaml:

    dh_auditor:
        audit_log:
            table_name: 'audit_log'
            connection: 'default'
        audit_log_entry:
            table_name: 'audit_log_entry'
            connection: 'default'
    
  3. Enable Auditing for an Entity Use the Auditable trait and annotations:

    use DH\AuditorBundle\Annotation as ORMAudit;
    
    #[ORM\Entity]
    #[ORMAudit\Auditable]
    class User
    {
        // ...
    }
    
  4. First Audit Log Run migrations (php bin/console doctrine:migrations:diff + php bin/console doctrine:migrations:migrate) and interact with your entity. Check the audit_log table for records.


First Use Case: Debugging Data Changes

  • View Audit Logs

    php bin/console dh:auditor:view
    

    Access the built-in viewer at /auditor (enabled by default).

  • Filter by Entity/Action Use the viewer’s UI or query directly:

    $auditLogRepository = $entityManager->getRepository(AuditLog::class);
    $logs = $auditLogRepository->findBy(['entityClass' => User::class]);
    

Implementation Patterns

Core Workflows

1. Entity Auditing

  • Automatic Tracking The bundle listens to Doctrine events (prePersist, preUpdate, preRemove) and logs changes to audit_log/audit_log_entry tables.

    • Custom Fields: Use #[ORMAudit\AuditField] to track specific properties:
      #[ORMAudit\AuditField]
      private ?string $email;
      
  • Bulk Operations For batch updates (e.g., EntityManager::createQueryBuilder()->update()), manually trigger audits:

    $auditor = $this->container->get('auditor');
    $auditor->audit($entity, 'update');
    

2. Custom Audit Providers

  • Extend Functionality Create a custom provider (e.g., for API logs):
    use DH\Auditor\Provider\ProviderInterface;
    
    class ApiAuditProvider implements ProviderInterface
    {
        public function audit($entity, $action, array $changes = []): void
        {
            // Custom logic (e.g., log to an external service)
        }
    }
    
    Register in services.yaml:
    services:
        DH\Auditor\Provider\ProviderInterface: '@api_audit_provider'
    

3. Symfony Messenger Integration

  • Long-Running Processes The bundle auto-tags DoctrineProvider with kernel.reset (since v7.2.0) to handle Messenger workers correctly. No config needed for basic use.

4. Querying Audit Data

  • Repository Methods Use the built-in repositories:
    $auditLogRepository = $entityManager->getRepository(AuditLog::class);
    $entries = $auditLogRepository->findByEntity(User::class, 1); // User with ID 1
    
  • Custom Queries Join with audit_log_entry for detailed changes:
    $qb = $entityManager->createQueryBuilder();
    $qb->select('al', 'ale')
       ->from(AuditLog::class, 'al')
       ->leftJoin('al.entries', 'ale')
       ->where('al.entityClass = :class')
       ->setParameter('class', User::class);
    

Integration Tips

Laravel-Specific Adaptations

  1. Service Registration In config/services.php, bind the auditor:

    'auditor' => \Illuminate\Support\Facades\App::make('auditor'),
    
  2. Doctrine Event Listeners Replace Symfony’s event system with Laravel’s:

    use Doctrine\ORM\Event\LifecycleEventArgs;
    use DH\AuditorBundle\Annotation\Auditable;
    
    class AuditableListener
    {
        public function preUpdate(LifecycleEventArgs $args): void
        {
            $entity = $args->getObject();
            if ($entity instanceof Auditable) {
                $auditor = app('auditor');
                $auditor->audit($entity, 'update');
            }
        }
    }
    

    Register in AppServiceProvider@boot():

    $em->getEventManager()->addEventListener(
        \Doctrine\ORM\Events::preUpdate,
        new AuditableListener()
    );
    
  3. Migrations Use Laravel Migrations to create audit tables:

    Schema::create('audit_log', function (Blueprint $table) {
        $table->id();
        $table->string('entity_class');
        $table->json('metadata')->nullable();
        $table->timestamps();
    });
    
  4. Route Configuration Add the auditor routes in routes/web.php:

    Route::prefix('auditor')->group(function () {
        \Illuminate\Support\Facades\Route::get('/', [\DamienHarper\AuditorBundle\Controller\AuditController::class, 'index']);
        // Add other routes as needed
    });
    

Gotchas and Tips

Pitfalls

  1. Schema Updates

    • Issue: Running php bin/console doctrine:schema:update --force may drop audit tables if not configured properly.
    • Fix: Exclude audit tables from schema updates or use migrations:
      # config/packages/doctrine.yaml
      doctrine:
          orm:
              schema_filter: '~^(?!audit_).*~'
      
  2. Circular References

    • Issue: Auditing entities with circular references (e.g., UserPost) may cause infinite loops.
    • Fix: Use #[ORMAudit\AuditIgnore] on problematic properties or limit depth:
      dh_auditor:
          audit_log_entry:
              max_depth: 3
      
  3. Performance

    • Issue: Heavy auditing can slow down writes.
    • Fix:
      • Disable for non-critical entities:
        #[ORMAudit\Auditable(disabled: true)]
        class LogEntry {}
        
      • Use async auditing (e.g., Symfony Messenger) for bulk operations.
  4. Symfony Messenger Workers

    • Issue: Audit logs may fail in long-running workers due to stale Doctrine state.
    • Fix: Ensure kernel.reset is enabled (auto-handled since v7.2.0). For older versions, manually tag the service:
      services:
          DH\Auditor\Provider\Doctrine\DoctrineProvider:
              tags: ['kernel.reset']
      

Debugging

  1. Enable Debug Logging Add to config/packages/monolog.yaml:

    handlers:
        dh_auditor:
            type: stream
            path: "%kernel.logs_dir%/dh_auditor.log"
            level: debug
            channels: ["auditor"]
    

    Then configure the bundle:

    dh_auditor:
        debug: true
    
  2. Check Audit Logs

    • SQL Queries: Enable Doctrine logging to see generated audit queries:
      doctrine:
          dbal:
              logging: true
              profiling: true
      
    • Manual Audit: Test with:
      $auditor = app('auditor');
      $auditor->audit($entity, 'update', ['field' => ['old' => 'old', 'new' => 'new']]);
      
  3. Common Errors

    • "Table does not exist": Run migrations or verify table_name in config.
    • "Class not auditable": Ensure the entity has #[ORMAudit\Auditable].
    • Empty audit entries: Check if audit_log_entry table exists and is linked correctly.

Tips

  1. Partial Auditing Audit only specific actions (e.g., update but not delete):

    #[ORMAudit\Auditable(actions: ['update'])]
    class Product {}
    
  2. Custom Metadata Attach extra data to audit logs:

    $auditor->audit($entity, 'update', [], [
        'source' => 'admin_panel',
        'user_id' => auth()->id(),
    ]);
    
  3. Audit Viewer Customization

    • Override Templates: Copy templates/auditor/ from the bundle to your project and modify
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.
phalcon/cli-options-parser
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/privacy-filter-classifier
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata