How jun-del/wr-audit-logger works
1. What this repo is
- wr-audit-logger is a TypeScript library, not an application.
- Its architecture sits at the Drizzle ORM / PostgreSQL boundary: application code uses a wrapped Drizzle database instance, and the library transparently records audit events for write operations.
2. Public surface
- The main entrypoint is src/index.ts.
- The package exposes:
- logger creation (createAuditLogger)
- audit table/schema helpers (createAuditTableSQL, createAuditTableSQLFor, createAuditLogsTable)
- shared types and the default audit table shape
- The README shows that the primary integration pattern is: create logger → replace db with the wrapped version → set per-request context → run normal inserts/updates/deletes.
3. Core interception layer
- src/core/interceptor.ts is the main control point.
- It wraps Drizzle operations so insert/update/delete calls can be observed without manual logging calls.
- src/core/AuditLogger.ts likely orchestrates this wrapper, config, context, and write strategy.
- src/core/context.ts provides request/job-scoped context so the audit record can carry user identity, IP, user agent, metadata, and transaction IDs.
4. Write-path data flow
- The normal application write hits the wrapped DB.
- The interceptor identifies the operation type and table.
- Capture modules extract the record identity and payload changes.
- A normalized audit event is produced.
- The event is persisted through the storage layer, unless a custom writer is configured.
- If strictMode is off, audit failures are meant to be isolated from the business write; if on, audit failure can fail the main operation.
5. Capture subsystem
- src/capture/insert.ts, update.ts, and delete.ts handle operation-specific extraction logic.
- This is where the library determines:
- action type
- affected table
- primary key / record ID
- values to store for the operation
- The README’s updateValuesMode setting implies this layer can emit either changed fields or full row snapshots for updates.
- The “auto-injected .returning()” behavior in the README indicates the capture layer can force row retrieval when the original query did not ask for returned data.
6. Storage subsystem
- src/storage/schema.ts and src/storage/column-map.ts define the audit table contract and how logical fields map to physical column names.
- src/storage/writer.ts is the default persistence path for a single audit record.
- src/storage/batch-writer.ts and src/storage/batched-custom-writer.ts add asynchronous buffering and flush behavior for high-throughput audit logging.
- This layer is where built-in audit rows are translated into SQL writes against the audit table.
7. Default schema vs custom storage
- The README makes a clear distinction between the built-in writer and customWriter.
- With the built-in writer, the library owns the audit schema contract and expects standard columns like user_id, action, table_name, record_id, values, metadata, and transaction_id.
- With customWriter, the library still computes the audit event, but the application takes over final persistence into any shape of table or sink it wants.
8. Utilities that support correctness
- src/utils/primary-key.ts resolves record identity from configured primary key fields.
- src/utils/serializer.ts handles stable conversion of values for storage in JSON/SQL-compatible form.
- src/utils/migration.ts supports schema creation/update helpers for the audit table.
- src/utils/metadata.ts and src/utils/logging.ts support derived metadata and internal diagnostics.
9. Type and config boundary
- src/types/config.ts and src/types/audit.ts define the public configuration and audit event shapes.
- These types reflect the repo’s main extension points:
- per-table primary key mapping
- field allowlists / exclusion lists
- audit table naming and column remapping
- batching behavior
- custom writers
- The types are important because this is a library whose correctness depends heavily on static schema alignment with Drizzle models.
10. Operational behavior
- The library is designed to preserve business transaction semantics while attaching audit context.
- The README’s transaction example shows that all operations inside a transaction share the same transaction_id.
- Batched mode introduces an async queue/flush boundary: writes can be buffered and flushed later, optionally waiting for persistence before returning.
11. Testing shape
- The test layout suggests strong emphasis on integration with real database behavior:
- tests/integration/* covers automatic audit capture, returning behavior, batch mode, and custom writer flows.
- tests/unit/* covers logger, batching, config, metadata, and SQL edge cases.
- This indicates the architecture is validated not just by isolated functions but by end-to-end DB interception behavior.
12. How to draw the architecture
- A good diagram would show:
- application code on the left
- wrapped Drizzle DB / transaction boundary in the middle
- interception and capture logic inside the library
- storage writer or custom writer on the right
- PostgreSQL audit table as the default sink
- request/job context feeding into the audit event
- The key architectural idea is that this library is a transparent audit pipeline attached to Drizzle writes, with optional batching and pluggable storage.
Main entry points: AuditLogger.ts Audit Logger · writer.ts Audit Writer · audit.ts Audit Types · interceptor.ts Interceptor
Components 21
Public API
Package entrypoints and shared contracts
- API Entry · Main package exports for logger creation, schema helpers, and shared types
src/index.ts - Config Types · Logger options, batching, custom writer, and table mapping settings
src/types/config.ts - Audit Types · Normalized audit event shape and default table contract
src/types/audit.ts
Core
Drizzle interception and orchestration
- Audit Logger · Builds the wrapped database, coordinates context, capture, and write strategy
src/core/AuditLogger.ts - Interceptor · Hooks Drizzle insert, update, and delete operations transparently
src/core/interceptor.ts - Request Context · Carries user, request, transaction, and metadata into audit events
src/core/context.ts
Capture
Operation-specific write extraction
- Insert Capture · Extracts insert action, table, identity, and row payload
src/capture/insert.ts - Update Capture · Extracts update action and either changed fields or row snapshots
src/capture/update.ts - Delete Capture · Extracts delete action and record identity
src/capture/delete.ts
Storage
Default audit persistence and batching
- Audit Writer · Persists a single audit row into the built-in audit table
src/storage/writer.ts - Batch Writer · Buffers audit rows and flushes them asynchronously or on demand
src/storage/batch-writer.ts - Custom Writer · Application-defined persistence path for audit events
src/storage/batched-custom-writer.ts - Audit Schema · Default audit table shape and SQL helpers
src/storage/schema.ts - Column Map · Maps logical audit fields onto physical column names
src/storage/column-map.ts
Utils
Helpers for identity, serialization, and migration
- Primary Key · Resolves record identity from configured primary key fields
src/utils/primary-key.ts - Serializer · Normalizes values for JSON and SQL-safe storage
src/utils/serializer.ts - Migration Helpers · Creates or updates the audit table schema
src/utils/migration.ts - Metadata Helpers · Derived metadata and internal diagnostics support
src/utils/metadata.ts
Tests
Integration and unit coverage
- Integration Tests · End-to-end capture, returning, batching, and custom writer coverage
tests/integration - Unit Tests · Logger, batching, config, metadata, and SQL edge cases
tests/unit
Other components
- Consumer App · Application code that uses the wrapped Drizzle database
Connections 35
- Consumer App → API Entry: uses API · Application imports logger creation and helper exports
- API Entry → Config Types: re-exports · Exposes public configuration types
- API Entry → Audit Types: re-exports · Exposes audit event and schema types
- API Entry → Audit Logger: creates · Primary entrypoint constructs the audit logger
- Audit Logger → Interceptor: wraps db · Builds the Drizzle interception layer
- Audit Logger → Request Context: attaches · Supplies request and transaction context to writes
- Audit Logger → Audit Writer: default sink · Uses built-in persistence when custom writer is absent
- Audit Logger → Batch Writer: optional batching · Can buffer audit writes for throughput
- Audit Logger → Custom Writer: pluggable sink · Can delegate persistence to application code
- Interceptor → Insert Capture: detects · Routes insert operations to capture logic
- Interceptor → Update Capture: detects · Routes update operations to capture logic
- Interceptor → Delete Capture: detects · Routes delete operations to capture logic
- Insert Capture → Primary Key: resolves id · Derives record identity for insert auditing
- Update Capture → Primary Key: resolves id · Derives record identity for update auditing
- Delete Capture → Primary Key: resolves id · Derives record identity for delete auditing
- Insert Capture → Serializer: normalizes · Serializes captured values for storage
- Update Capture → Serializer: normalizes · Serializes changed fields or snapshots
- Delete Capture → Serializer: normalizes · Serializes delete payload data
- Insert Capture → Audit Types: emits · Produces normalized audit events
- Update Capture → Audit Types: emits · Produces normalized audit events
- Delete Capture → Audit Types: emits · Produces normalized audit events
- Audit Writer → Audit Schema: writes to · Persists audit rows into the default audit table
- Audit Writer → Column Map: maps fields · Translates logical audit fields to table columns
- Audit Writer → Migration Helpers: supports · Works with schema creation and update helpers
- Batch Writer → Audit Writer: flushes to · Batched mode eventually uses the default writer path
- Batch Writer → Custom Writer: buffers for · Buffered writes can target a custom sink
- Audit Schema → Migration Helpers: defines · Schema contract feeds table creation helpers
- Request Context → Audit Types: enriches · Context fields are attached to audit events
- Metadata Helpers → Audit Types: enriches · Derived metadata is included in audit payloads
- Integration Tests → Interceptor: verifies · Covers transparent interception behavior
- Integration Tests → Audit Writer: verifies · Covers built-in persistence flows
- Integration Tests → Batch Writer: verifies · Covers buffered and async flush behavior
- Integration Tests → Custom Writer: verifies · Covers pluggable writer flows
- Unit Tests → Audit Logger: verifies · Covers orchestration and config edges
- Unit Tests → Serializer: verifies · Covers value normalization cases