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¶
- 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
DATABASE_URL: Audit logging uses the same Prismadbsingleton as the rest of the API. No separate credentials needed.
How It Works¶
- Event Emission: Controllers emit events using
emitEvent():
```typescript import { emitEvent } from "../services/EventBus";
emitEvent("create", "invoice", invoiceId, userId, { document_number: invoice.document_number, }); ```
-
Event Bus: The backend event bus receives all events
-
Audit Subscriber: Listens to all
create,update,deleteevents: - Calculates diffs for update operations
- Inserts audit logs into the database via the shared Prisma client
-
Non-blocking (errors don't break the application)
-
Database: Audit logs are stored in the
audittable with: event_type: create/update/delete/notifyentity: invoice/customer/product/etc.entity_id: UUID of the affected entityactor_id: User who triggered the eventdiff: JSON diff for updates, or event detailsmetadata: Optional additional context- Legacy fields for backward compatibility
Verification¶
To verify audit logging is working:
- Check Logs: Watch for
[AuditSubscriber]debug messages in the console - Query Database: Check the
audittable for new entries
sql
SELECT * FROM audit
ORDER BY created_at DESC
LIMIT 10;
- Test Event: Create, update, or delete an entity and check the audit log
Troubleshooting¶
No Audit Logs Being Created¶
-
Check
DATABASE_URL: Audit logging uses the same connection as the rest of the API — if the API can serve requests, audit can write. -
Check Console Logs: Look for initialization messages:
[AuditSubscriber] Initializing audit logging subscriber
[AuditSubscriber] Initialized successfully
- 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¶
- Audit Log Retention:
- Consider implementing automatic cleanup for old logs
-
Set up database archiving for compliance
-
Performance:
- Audit logging is asynchronous and non-blocking
- Failed audit logs don't affect business operations
- Consider indexing the
audittable for better query performance
Related Documentation¶
- Event Bus Architecture
- Generic Event System
- Database Migration:
database/migrations/001_audit_table_refactor.sql