A customizable logger using Winston and CLS-Hooked for correlation IDs.
npm install @1001tv/logger1001tv-logger is a customizable logging library built on top of Winston with support for CLS-Hooked for correlation IDs. This library is designed for use across multiple TypeScript projects, providing structured logging with mandatory and optional metadata fields for 1001tv services.
- Structured Logging: Logs are formatted in JSON, making them easy to parse and analyze using log aggregation tools like AWS CloudWatch.
- Correlation IDs: Automatically injects correlation IDs into logs from CLS-Hooked, ensuring that all logs from a single request are grouped together and making it easy to trace requests across distributed.
- Customizable Log Levels: Supports custom log levels (error, warn, info).
layer (mandatory): Indicates the layer where the log is generated (e.g., 'main', 'service', 'controller', 'repository', 'middleware', 'other').
function (mandatory): The name of the function where the log is printed.
Any additional fields can be included as optional metadata (e.g., userId, errorCode).
1- Basic Setup
Import the logger into your project:
``ts`
import { logInfo, logError } from '1001-logger';
2- Logging Examples
Info Logging
`ts
logInfo('This is an informational message');
// Or
logInfo('This is an informational message', {
layer: 'service', // Mandatory metadata
function: 'fetchData', // Mandatory metadata
userId: '1234' // Optional metadata
});
`
Warn Logging
`ts
logWarn('This is a warning message');
// Or
logWarn('This is a warning message', {
layer: 'controller', // Mandatory
function: 'handleRequest', // Mandatory metadata
userId: '5678' // Optional metadata
});
`
Error Logging
`ts
logError('This is an error message');
// Or
logError('This is an error message', {
layer: 'controller', // Mandatory metadata
function: 'handleRequest', // Mandatory metadata
errorCode: 'ERR123', // Optional metadata
userId: '5678' // Optional metadata
});
`
Example:
`ts
// Ensure a correlation ID is set up earlier in the middleware or service
import { Request, Response, NextFunction } from 'express';
import { createNamespace } from 'cls-hooked';
const session = createNamespace('auth-middleware-namespace');
export function storeCorrelationIdMiddleware(req: Request, res: Response, next: NextFunction) {
session.run(() => {
session.set('correlationId', req.headers['x-correlation-id']);
next();
});
}
``