I'll help you create a robust Enterprise-level Audit Logging system using Node.js, Express, TypeScript, and TypeORM. This system will track user actions, database changes, and system events.
First, let's create the necessary files and structure:
- First, the Audit Log Entity:
// src/entities/AuditLog.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from "typeorm";
@Entity("audit_logs")
export class AuditLog {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column()
action: string;
@Column()
entityName: string;
@Column({ nullable: true })
entityId: string;
@Column({ type: "json", nullable: true })
oldValues: Record<string, any>;
@Column({ type: "json", nullable: true })
newValues: Record<string, any>;
@Column({ nullable: true })
userId: string;
@Column({ nullable: true })
userEmail: string;
@Column({ nullable: true })
ipAddress: string;
@Column({ nullable: true })
userAgent: string;
@CreateDateColumn()
createdAt: Date;
}
- Create an Audit Service:
// src/services/AuditService.ts
import { getRepository } from "typeorm";
import { AuditLog } from "../entities/AuditLog.entity";
import { Request } from "express";
export class AuditService {
private static instance: AuditService;
private constructor() {}
static getInstance(): AuditService {
if (!AuditService.instance) {
AuditService.instance = new AuditService();
}
return AuditService.instance;
}
async log(params: {
action: string;
entityName: string;
entityId?: string;
oldValues?: Record<string, any>;
newValues?: Record<string, any>;
userId?: string;
userEmail?: string;
request?: Request;
}): Promise<void> {
const auditLogRepo = getRepository(AuditLog);
const auditLog = new AuditLog();
auditLog.action = params.action;
auditLog.entityName = params.entityName;
auditLog.entityId = params.entityId;
auditLog.oldValues = params.oldValues;
auditLog.newValues = params.newValues;
auditLog.userId = params.userId;
auditLog.userEmail = params.userEmail;
if (params.request) {
auditLog.ipAddress = params.request.ip;
auditLog.userAgent = params.request.get("user-agent");
}
await auditLogRepo.save(auditLog);
}
}
- Create a TypeORM Subscriber for automatic entity changes tracking:
// src/subscribers/AuditSubscriber.ts
import { EventSubscriber, EntitySubscriberInterface, InsertEvent, UpdateEvent, RemoveEvent } from "typeorm";
import { AuditService } from "../services/AuditService";
@EventSubscriber()
export class AuditSubscriber implements EntitySubscriberInterface {
private auditService = AuditService.getInstance();
async afterInsert(event: InsertEvent<any>): Promise<void> {
await this.auditService.log({
action: "CREATE",
entityName: event.metadata.targetName,
entityId: event.entity.id,
newValues: event.entity,
});
}
async beforeUpdate(event: UpdateEvent<any>): Promise<void> {
await this.auditService.log({
action: "UPDATE",
entityName: event.metadata.targetName,
entityId: event.entity.id,
oldValues: event.databaseEntity,
newValues: event.entity,
});
}
async beforeRemove(event: RemoveEvent<any>): Promise<void> {
await this.auditService.log({
action: "DELETE",
entityName: event.metadata.targetName,
entityId: event.entity.id,
oldValues: event.entity,
});
}
}
- Create a middleware for Express to attach user information:
// src/middleware/auditMiddleware.ts
import { Request, Response, NextFunction } from "express";
import { AuditService } from "../services/AuditService";
export const auditMiddleware = (
req: Request & { user?: any },
res: Response,
next: NextFunction
) => {
const originalSend = res.send;
res.send = function (body?: any): Response {
const auditService = AuditService.getInstance();
auditService.log({
action: `HTTP_${req.method}`,
entityName: req.path,
userId: req.user?.id,
userEmail: req.user?.email,
request: req,
newValues: {
body: req.body,
query: req.query,
params: req.params,
response: body,
},
});
return originalSend.call(this, body);
};
next();
};
- Usage example in your Express application:
// src/app.ts
import express from "express";
import { createConnection } from "typeorm";
import { auditMiddleware } from "./middleware/auditMiddleware";
import { AuditSubscriber } from "./subscribers/AuditSubscriber";
async function bootstrap() {
// Initialize TypeORM connection
await createConnection({
// your database configuration
subscribers: [AuditSubscriber],
});
const app = express();
// Apply middleware
app.use(express.json());
app.use(auditMiddleware);
// Example route with manual audit logging
app.post("/api/users", async (req, res) => {
try {
// Your user creation logic here
const auditService = AuditService.getInstance();
await auditService.log({
action: "USER_REGISTRATION",
entityName: "User",
entityId: newUser.id,
newValues: req.body,
request: req,
});
res.status(201).json(newUser);
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
}
bootstrap();
- Add a utility to query audit logs:
// src/utils/AuditQueryUtil.ts
import { getRepository, Between, FindManyOptions } from "typeorm";
import { AuditLog } from "../entities/AuditLog.entity";
export class AuditQueryUtil {
static async queryAuditLogs(params: {
startDate?: Date;
endDate?: Date;
userId?: string;
action?: string;
entityName?: string;
entityId?: string;
page?: number;
limit?: number;
}) {
const auditLogRepo = getRepository(AuditLog);
const query: FindManyOptions<AuditLog> = {
where: {},
order: { createdAt: "DESC" },
skip: (params.page - 1) * params.limit || 0,
take: params.limit || 10,
};
if (params.startDate && params.endDate) {
query.where = {
...query.where,
createdAt: Between(params.startDate, params.endDate),
};
}
if (params.userId) {
query.where = { ...query.where, userId: params.userId };
}
if (params.action) {
query.where = { ...query.where, action: params.action };
}
if (params.entityName) {
query.where = { ...query.where, entityName: params.entityName };
}
if (params.entityId) {
query.where = { ...query.where, entityId: params.entityId };
}
const [logs, total] = await auditLogRepo.findAndCount(query);
return { logs, total };
}
}
This audit logging system provides:
- Automatic tracking of database changes (create, update, delete)
- HTTP request logging
- User action tracking
- IP address and user agent logging
- Flexible query capabilities
- Singleton pattern for the audit service
- TypeORM integration
- Middleware for Express
- Pagination and filtering support
To enhance this system further, you could:
- Add data encryption for sensitive information
- Implement log rotation
- Add export functionality (CSV, PDF)
- Create a dashboard for viewing audit logs
- Add real-time notifications for specific audit events
- Implement log archiving strategy
- Add more detailed error logging
Would you like me to elaborate on any of these aspects or show how to implement any of the additional features?