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

caxy/audit-log-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require caxy/audit-log-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Caxy\AuditLogBundle\CaxyAuditLogBundle::class => ['all' => true],
    ];
    
  2. Configure Database: Update config/packages/doctrine.yaml to include the audit log schema:

    doctrine:
        orm:
            mappings:
                CaxyAuditLogBundle: ~
    

    Run migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  3. Enable Auditing for an Entity: Annotate your entity with @AuditLog and define fields to track:

    use Caxy\AuditLogBundle\Annotation\AuditLog;
    
    /**
     * @AuditLog(fields={"name", "status", "createdAt"})
     */
    class Product {}
    
  4. First Use Case: Test by creating/updating a Product entity. Check the audit_log table for records:

    php bin/console doctrine:query:sql "SELECT * FROM audit_log"
    

Implementation Patterns

Workflows

  1. Entity-Level Auditing:

    • Use @AuditLog on entities to auto-track changes to specified fields.
    • Example: Track User profile updates:
      /**
       * @AuditLog(fields={"email", "role", "lastLogin"})
       */
      class User {}
      
  2. Bulk Operations:

    • Audit log captures changes in bulk operations (e.g., EntityManager::flush()).
    • Useful for admin actions like mass-updating records.
  3. Soft Deletes:

    • Combine with SoftDeleteable trait to audit deletions:
      use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
      
      class Product {
          use SoftDeleteableEntity;
          // ...
      }
      
    • Audit log will record deletedAt changes.
  4. Custom Actions:

    • Log manual actions via events:
      use Caxy\AuditLogBundle\Event\AuditLogEvent;
      
      $event = new AuditLogEvent($entity, 'MANUAL_ACTION', ['note' => 'Custom action']);
      $dispatcher->dispatch(AuditLogEvents::AUDIT_LOG, $event);
      

Integration Tips

  • Symfony Events: Listen to audit_log.post_persist or audit_log.post_update for post-processing:

    # config/services.yaml
    services:
        App\EventListener\AuditLogListener:
            tags:
                - { name: kernel.event_listener, event: audit_log.post_persist, method: onAuditLogPersist }
    
  • Doctrine Lifecycle Callbacks: Use prePersist/preUpdate to enrich audit data:

    class Product {
        public function preUpdate() {
            $this->setUpdatedBy($this->getUser()->getId());
        }
    }
    
  • APIs: Expose audit logs via API (e.g., using API Platform):

    use ApiPlatform\Core\Annotation\ApiResource;
    
    /**
     * @ApiResource()
     */
    class AuditLog {}
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Audit logging adds queries per entity change. For high-traffic apps:
      • Disable for non-critical entities.
      • Use @AuditLog(ignoreFields={"largeBinaryField"}) to exclude bloated fields.
  2. Schema Migrations:

    • The bundle assumes the audit_log table exists. Manual schema changes may break it.
    • Fix: Always run migrations after bundle updates.
  3. Circular References:

    • Auditing relationships (e.g., @ManyToOne) can cause infinite loops.
    • Fix: Exclude related fields or use fetch="LAZY" in Doctrine.
  4. Symfony 4+ Compatibility:

    • Bundle is outdated (last release 2015). May require patches for modern Symfony.
    • Tip: Fork and update composer.json to support Symfony 4.4+:
      "require": {
          "symfony/framework-bundle": "^4.4|^5.0"
      }
      

Debugging

  • Missing Logs:

    • Check if the bundle is enabled in bundles.php.
    • Verify Doctrine event listeners are registered:
      php bin/console debug:event-dispatcher | grep audit
      
  • Incorrect Fields:

    • Audit log only tracks fields listed in @AuditLog(fields={...}). Omit fields to exclude them.
  • Timestamp Issues:

    • If updatedAt is missing, ensure Doctrine lifecycle callbacks are set:
      use Gedmo\Timestampable\Traits\TimestampableEntity;
      
      class Product {
          use TimestampableEntity;
      }
      

Extension Points

  1. Custom Storage:

    • Override the AuditLogStorage service to log to external systems (e.g., Elasticsearch):
      services:
          app.audit_log.storage:
              class: App\Service\ElasticsearchAuditLogStorage
              decorates: caxy_audit_log.storage
      
  2. Field Transformations:

    • Use preAuditLog event to modify payload before storage:
      public function onPreAuditLog(AuditLogEvent $event) {
          $event->setData(array_merge($event->getData(), ['ip' => $this->getClientIp()]));
      }
      
  3. Access Control:

    • Restrict audit log access via voters:
      use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
      
      class AuditLogVoter implements VoterInterface {
          public function supports(string $attribute, $subject) {
              return $attribute === 'VIEW_AUDIT_LOG';
          }
      }
      
  4. Bulk Audit Optimization:

    • For bulk operations, batch inserts to reduce DB load:
      $em->flush();
      $em->getConnection()->beginTransaction();
      // Batch audit logs here
      $em->getConnection()->commit();
      

---
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.
amashukov/lnd-client-php
althinect/enum-permission
andydefer/laravel-actions
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
spatie/mailcoach-vapor