@ochoche/audit-log
v1.0.1
Published
NestJS Audit Log Module with Prisma
Downloads
130
Readme
Audit Log System (NestJS + Prisma + PostgreSQL)
Overview
This project implements an audit logging system using NestJS, Prisma, and PostgreSQL.
It automatically records user/system actions (CREATE, UPDATE, DELETE, GET) with metadata such as IP address, device info, and location.
The goal is to provide accountability and traceability for application events.
Features
- NestJS Interceptor for automatic logging of requests
- Prisma ORM with PostgreSQL for structured storage
- Captures:
- Action type (CREATE, UPDATE, DELETE, GET)
- Entity and entity ID
- Before and after state
- IP address
- Device info
- Location (via GeoIP lookup)
- Timestamp
Installation
npm i @ochoche/audit-logSetup Instructions
1. Add the AuditLog model to your Prisma schema
model AuditLog {
id String @id @default(uuid())
action String
entity String
entityId String?
beforeState Json?
afterState Json?
ipAddress String?
deviceInfo String?
location String?
timestamp DateTime @default(now())
}Run migrations:
npx prisma migrate dev --name add_audit_log
npx prisma generate2. Configure environment variables
Create a .env file with your database connection:
DATABASE_URL="postgresql://user:password@localhost:5432/auditlogdb"
npm install3. Import the module
In your app.module.ts:
import { Module } from '@nestjs/common';
import { AuditLogModule } from '@ochoche/audit-log';
@Module({
imports: [AuditLogModule],
})
export class AppModule {}4. Apply the interceptor globally
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AuditLogInterceptor } from '@ochoche/audit-log';
import { AuditlogService } from '@ochoche/audit-log';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const auditLogService = app.get(AuditlogService);
app.useGlobalInterceptors(new AuditLogInterceptor(auditLogService));
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();Usage
You can also inject the service directly for manual logging:
import { AuditLogService } from '@ochoche/audit-log';
@Injectable()
export class OrdersService {
constructor(private readonly auditLogService: AuditLogService) {}
async updateOrder(orderId: string, data: any) {
// ... update logic
await this.auditLogService.createLog({
action: 'UPDATE',
entity: 'Order',
entityId: orderId,
beforeState: { /* old data */ },
afterState: { /* new data */ },
ipAddress: '127.0.0.1',
deviceInfo: 'Mozilla/5.0',
location: 'Nigeria',
});
}
}Author
Ochoche
