Audit Logging Setup

See also: Development Setup for environment configuration | Event Bus Architecture for how events work

Overview

The audit logging system automatically tracks all create, update, and delete events in the database. It uses the generic event bus architecture and stores audit logs in the audit table.

Prerequisites

  1. Database Migration: Run the audit table migration to add new columns:

sql -- File: database/migrations/001_audit_table_refactor.sql -- Adds: event_type, entity, entity_id, metadata columns

  1. DATABASE_URL: Audit logging uses the same Prisma db singleton as the rest of the API. No separate credentials needed.

How It Works

  1. Event Emission: Controllers emit events using emitEvent():

```typescript import { emitEvent } from "../services/EventBus";

emitEvent("create", "invoice", invoiceId, userId, { document_number: invoice.document_number, }); ```

  1. Event Bus: The backend event bus receives all events

  2. Audit Subscriber: Listens to all create, update, delete events:

  3. Calculates diffs for update operations
  4. Inserts audit logs into the database via the shared Prisma client
  5. Non-blocking (errors don't break the application)

  6. Database: Audit logs are stored in the audit table with:

  7. event_type: create/update/delete/notify
  8. entity: invoice/customer/product/etc.
  9. entity_id: UUID of the affected entity
  10. actor_id: User who triggered the event
  11. diff: JSON diff for updates, or event details
  12. metadata: Optional additional context
  13. Legacy fields for backward compatibility

Verification

To verify audit logging is working:

  1. Check Logs: Watch for [AuditSubscriber] debug messages in the console
  2. Query Database: Check the audit table for new entries

sql SELECT * FROM audit ORDER BY created_at DESC LIMIT 10;

  1. Test Event: Create, update, or delete an entity and check the audit log

Troubleshooting

No Audit Logs Being Created

  1. Check DATABASE_URL: Audit logging uses the same connection as the rest of the API — if the API can serve requests, audit can write.

  2. Check Console Logs: Look for initialization messages:

[AuditSubscriber] Initializing audit logging subscriber [AuditSubscriber] Initialized successfully

  1. Check Error Messages: Look for database errors in the console

Migration Not Applied

Run the migration manually:

psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f database/migrations/001_audit_table_refactor.sql

Security Considerations

  1. Audit Log Retention:
  2. Consider implementing automatic cleanup for old logs
  3. Set up database archiving for compliance

  4. Performance:

  5. Audit logging is asynchronous and non-blocking
  6. Failed audit logs don't affect business operations
  7. Consider indexing the audit table for better query performance