Advanced audit logging and trail package supporting multiple databases with dynamic columns, log levels, and customizable console logs.
npm install audit-proAudit Pro is an advanced audit logging and trail package for Node.js applications that supports multiple databases with dynamic columns, log levels, and customizable console logs. It enables developers to log, retrieve, and manage audit events easily and efficiently.
- Audit Pro
- Table of Contents
- Installation
- Storage Dependencies
- Getting Started
- Basic Setup
- Usage
- Using Storage Instance to Log Events
- Logging Events
- Fetching Logs
- Updating Logs
- Deleting Logs
- Counting Logs
- API Documentation
- AuditLogger
- Constructor
- Methods
- Storage Interfaces
- ConsoleLogger
- Constructor
- Methods
- Available Log Levels
- Viewing Logs
- Customizing Console Logs
- Examples
- Testing
- License
To install the audit-pro package, use npm:
``bash`
npm install audit-pro
Depending on which storage type you plan to use, you may need to install additional dependencies:
- Sequelize (for SQL databases): If you intend to use Sequelize for SQL-based storage (e.g., MySQL, PostgreSQL), you must install sequelize and a corresponding SQL driver (e.g., mysql2, pg).
`bash`
npm install sequelize
- MongoDB: If you are using MongoDB as your storage, install the mongodb package.
`bash`
npm install mongodb
To start using Audit Pro, you need to create instances of the AuditLogger, the storage implementations (like SequelizeStorage or FileStorage), and the ConsoleLogger.
`typescript
import { SequelizeStorage, LogLevel, AuditLogInterface } from 'audit-pro';
import { DataTypes, Model, ModelAttributes, Sequelize } from 'sequelize';
// Setup your database connection
const sequelizeInstance = new Sequelize('mysql://user:password@localhost:3306/audit', {
logging: false,
});
// Create storage and logger instances
const storage = new SequelizeStorage(sequelizeInstance, 'AuditLogs', {});
const logger = new ConsoleLogger(true); // true enables console logging
// Create an AuditLogger instance
const auditLogger = new AuditLogger(storage, logger);
OR
Using Storage Instance to Log Events
// Define dynamic columns (if any)
const dynamicColumns: Partial
additionalInfo: {
type: DataTypes.STRING,
allowNull: true,
},
};
// Create the storage instance with the necessary table name and dynamic columns
const storage = new SequelizeStorage(sequelizeInstance, 'AuditLogs', dynamicColumns);
`
`typescript
// Create the storage instance with the necessary table name and dynamic columns
const storage = new SequelizeStorage(sequelizeInstance, 'AuditLogs', dynamicColumns);
// Example of logging an event
const logEvent: AuditLogInterface = {
id: 'unique-log-id',
userId: 'user123',
action: 'User Login',
logLevel: LogLevel.INFO,
timestamp: new Date(),
metadata: { ipAddress: '192.168.1.1' },
additionalInfo: 'extra information'
// more custom fields on the dynamic column
};
// Log the event directly using the storage instance
await storage.logEvent(logEvent);
`
To log an event, use the logEvent method. The method accepts an AuditLogInterface object.
`typescript
const log: AuditLogInterface = {
id: 'unique-log-id',
userId: 'user123',
action: 'User Login',
logLevel: LogLevel.INFO,
timestamp: new Date(),
metadata: { ipAddress: '192.168.1.1' },
//any additional fields
};
// Log the event
await auditLogger.logEvent(log);
`
You can retrieve logs with specific filters using the fetchLogs method.
`typescript`
const logs = await auditLogger.fetchLogs({ userId: 'user123' });
console.log(logs);
To update an existing log, use the updateLog method.
`typescript`
await auditLogger.updateLog('unique-log-id', { action: 'Updated Action' });
You can delete logs by using the deleteLog method.
`typescript`
await auditLogger.deleteLog('unique-log-id');
To count logs based on specific filters, use the countLogs method.
`typescriptTotal logs for user123: ${count}
const count = await auditLogger.countLogs({ userId: 'user123' });
console.log();`
The AuditLogger class is the main entry point for logging events.
#### Constructor
`typescript`
new AuditLogger(storage: StorageInterface, logger: ConsoleLogger)
- storage: An instance of a storage implementation (e.g., SequelizeStorage, FileStorage).ConsoleLogger
- logger: An instance of for logging to the console.
#### Methods
- logEvent(log: AuditLogInterface): PromisefetchLogs(filter: object): Promise
- fetchLog(filter: object): Promise
- updateLog(id: string, updates: object): Promise
- deleteLog(id: string): Promise
- countLogs(filter: object): Promise
-
Implement your storage interface by extending StorageInterface. The main methods to implement are:
- logEvent(log: AuditLogInterface): PromisefetchLogs(filter: object): Promise
- updateLog(id: string, updates: object): Promise
- deleteLog(id: string): Promise
- countLogs(filter: object): Promise
-
The ConsoleLogger class is used for logging events to the console.
#### Constructor
`typescript`
new ConsoleLogger(isEnabled: boolean)
- isEnabled: Boolean indicating whether console logging is enabled.
#### Methods
- getIsEnabled(): booleanlogEventToConsole(log: AuditLogInterface): void
- colorize(message: string, color: Color): string
-
- LogLevel.INFO
- LogLevel.WARN
- LogLevel.ERROR
- LogLevel.DEBUG
- LogLevel.CUSTOM
You can use the LogViewer class to fetch and display logs from any storage implementation. Here’s an example:
`typescript
import { LogViewer, ConsoleLogger } from 'audit-pro';
const consoleLogger = new ConsoleLogger(true); // Enable colorized console logging
// Assuming you have configured one or more storages
const logViewer = new LogViewer([storage], consoleLogger);
// View logs based on filters (e.g., userId)
logViewer.viewLogs({ userId: 'user123' });
`
Audit-Pro allows you to customize the console output with different colors:
`typescript
import { ConsoleLogger } from 'audit-pro';
// Enable colorized logs
const consoleLogger = new ConsoleLogger(true);
// Log events to the console
consoleLogger.logEventToConsole({
id: 'unique-log-id',
userId: 'user123',
action: 'User Login',
logLevel: LogLevel.INFO,
timestamp: new Date(),
metadata: { ipAddress: '192.168.1.1' },
});
`
Here’s a simple example of how to use Audit Pro in an Express.js application.
`typescript
import express from 'express';
import { AuditLogger, ConsoleLogger, SequelizeStorage } from 'audit-pro';
import { Sequelize } from 'sequelize';
const app = express();
const sequelizeInstance = new Sequelize('mysql://user:password@localhost:3306/audit', {
logging: false,
});
const storage = new SequelizeStorage(sequelizeInstance, 'AuditLogs', {});
const logger = new ConsoleLogger(true);
const auditLogger = new AuditLogger(storage, logger);
app.post('/login', async (req, res) => {
// Simulating a login action
const log: AuditLogInterface = {
id: 'unique-log-id',
userId: req.body.userId,
action: 'User Login',
logLevel: LogLevel.INFO,
timestamp: new Date(),
metadata: { ipAddress: req.ip },
};
await auditLogger.logEvent(log);
res.send('Login logged!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
`
To run the tests for Audit Pro, ensure you have Jest installed. Run the following command:
`bash``
npm test
This project is licensed under the MIT License - see the LICENSE file for details.