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

Audit Bundle Laravel Package

cgarcia/audit-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cgarcia/audit-bundle
    

    Add to AppKernel.php:

    new DataDog\AuditBundle\DataDogAuditBundle(),
    
  2. Database Setup Run migrations or schema update:

    php app/console doctrine:migrations:diff
    php app/console doctrine:migrations:migrate
    

    Alternative:

    php app/console doctrine:schema:update --force
    
  3. First Use Case

    • Perform a CRUD operation (e.g., User entity update via Symfony form).
    • Check logs at /audit (demo route) to verify captured changes.

Implementation Patterns

Core Workflow

  1. Automatic Logging

    • All Doctrine ORM operations (persist(), merge(), remove(), flush()) are audited without manual intervention.
    • Example: Updating a Product entity triggers an audit entry with:
      • Timestamp, user (if authenticated), entity type (Product), and diff of changed fields.
  2. Transaction Safety

    • Audit entries are inserted within the same transaction as the original operation.
    • Rollback on failure ensures no orphaned audit logs.
  3. Relation Tracking

    • One-to-Many/Many-to-One: Logs association/dissociation actions (e.g., adding/removing a Tag from a Post).
    • Many-to-Many: Captures changes in join tables (e.g., PostTag updates).
  4. User Attribution

    • Links audit entries to the authenticated user via Symfony’s TokenStorage.
    • Requires SecurityBundle and a logged-in user.

Integration Tips

  • Custom Entities: Exclude sensitive entities by annotating them with @AuditIgnore:
    use DataDog\AuditBundle\Annotation\AuditIgnore;
    /**
     * @AuditIgnore
     */
    class CreditCard {}
    
  • Event Listeners: Extend audit behavior by subscribing to audit.log events:
    # services.yml
    services:
        app.audit_listener:
            class: AppBundle\EventListener\CustomAuditListener
            tags:
                - { name: kernel.event_listener, event: audit.log, method: onAuditLog }
    
  • Query Filtering: Restrict audit logs by entity/date in your /audit controller:
    $auditRepo = $this->get('audit.repository');
    $logs = $auditRepo->findBy(['entityClass' => 'AppBundle\Entity\Product']);
    

Gotchas and Tips

Pitfalls

  1. No DQL/SQL Tracking

    • Issue: Direct SQL (EntityManager::createNativeQuery()) or DQL bypasses the bundle.
    • Workaround: Use ORM methods ($em->persist()) or wrap SQL in a service with manual audit logging.
  2. Performance Overhead

    • Issue: Audit logs add latency during flush().
    • Mitigation: Disable for bulk operations:
      $em->getConnection()->getConfiguration()->setSQLLogger(null);
      $em->flush(); // No audit logs generated
      
  3. User Attribution Gaps

    • Issue: Anonymous users appear as null in audit logs.
    • Fix: Implement a fallback user (e.g., System):
      // In a listener
      $user = $tokenStorage->getToken()?->getUser() ?: new AnonymousUser();
      
  4. Many-to-Many Edge Cases

    • Issue: Complex join table updates may produce unclear diffs.
    • Debug: Inspect raw SQL via doctrine.event_listeners.orm.default logging.

Debugging

  • Enable Logging: Add to config.yml:
    doctrine:
        dbal:
            logging: true
            profiling: true
    
  • Check Events: Verify audit.log events fire in dev.log:
    grep "audit.log" app/logs/dev.log
    

Extension Points

  1. Custom Fields Add metadata to audit logs via event subscriber:
    public function onAuditLog(AuditLogEvent $event) {
        $event->getLog()->setMetadata(['custom_field' => 'value']);
    }
    
  2. Async Logging Offload audit writes to a queue (e.g., Symfony Messenger) for high-traffic apps.
  3. Webhook Notifications Extend the bundle to trigger webhooks on critical changes (e.g., User updates):
    public function onAuditLog(AuditLogEvent $event) {
        if ($event->getLog()->getEntityClass() === User::class) {
            $this->dispatchWebhook($event->getLog());
        }
    }
    

Configuration Quirks

  • Entity Whitelisting: Defaults to auditing all entities. Explicitly opt-in/out:
    # config.yml
    data_dog_audit:
        entities:
            include: ['AppBundle\Entity\Product']
            exclude: ['AppBundle\Entity\CreditCard']
    
  • Flush Timing: Audit logs are written after the main transaction commits. For immediate visibility, use flush() + clear().
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware