@whdigitalbuild/wh_track_log
v1.0.0
Published
Serilog-compatible logging for Node.js and NestJS with CloudWatch support
Readme
@dtducas/wh-log-track
Serilog-compatible logging package for Node.js and NestJS applications with AWS CloudWatch support.
Documentation
- 📖 Usage Guide - Complete usage documentation
- 🔧 API Reference - Detailed API documentation
- 📝 Examples - Working code examples
- 🤝 Contributing - Development guide
Features
- ✅ Serilog Compact JSON Format - 100% compatible with .NET Serilog output
- ✅ CloudWatch Integration - Direct logging to AWS CloudWatch Logs
- ✅ Hybrid Support - Works with both Express and NestJS applications
- ✅ Message Templates - Serilog-style message templates with placeholders
- ✅ Request Logging - Automatic HTTP request/response logging
- ✅ Multiple Output Formats - JSON, Pretty, or Serilog template formats
- ✅ TypeScript - Full TypeScript support with type definitions
Installation
npm install wh-log-trackPeer Dependencies
For NestJS projects:
npm install @nestjs/common @nestjs/core rxjsFor Express projects:
npm install expressQuick Start
For NestJS Applications
1. Configure the module in app.module.ts:
import { WhLogTrackModule } from 'wh-log-track';
@Module({
imports: [
WhLogTrackModule.forRoot({
appName: 'my-nestjs-app',
useCloudWatch: true, // Enable CloudWatch in production
useConsole: true, // Enable console logging
consoleFormat: 'pretty', // Use pretty format for development
}),
],
})
export class AppModule {}2. Use the logger in main.ts:
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { WhRequestLoggingInterceptor, WhExceptionFilter } from 'wh-log-track';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Use Winston logger
app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
// Add request logging interceptor
app.useGlobalInterceptors(
new WhRequestLoggingInterceptor(app.get(WINSTON_MODULE_NEST_PROVIDER))
);
// Add exception filter
app.useGlobalFilters(
new WhExceptionFilter(app.get(WINSTON_MODULE_NEST_PROVIDER))
);
await app.listen(3000);
}
bootstrap();For Express Applications
import express from 'express';
import { whLogMiddleware, whErrorMiddleware } from 'wh-log-track';
const app = express();
// Add request logging middleware (should be early in the pipeline)
app.use(whLogMiddleware({
appName: 'my-express-app',
useCloudWatch: process.env.NODE_ENV === 'production',
useConsole: true,
consoleFormat: 'pretty',
}));
// Your routes
app.get('/api/users', (req, res) => {
res.json({ users: [] });
});
// Add error logging middleware (should be after routes)
app.use(whErrorMiddleware());
app.listen(3000);Configuration
Basic Options
interface WhLogTrackOptions {
appName: string; // Required: Your application name
useCloudWatch: boolean; // Enable CloudWatch logging
useConsole: boolean; // Enable console logging
logGroupName?: string; // Custom log group name (default: /ecs/{appName}-requests)
region?: string; // AWS region (default: ap-southeast-1)
consoleFormat?: 'json' | 'pretty' | 'serilog'; // Console output format
minLevel?: string; // Minimum log level (default: info)
}CloudWatch Configuration
WhLogTrackModule.forRoot({
appName: 'my-app',
useCloudWatch: true,
cloudWatch: {
batchSize: 100, // Number of logs to batch (default: 100)
flushInterval: 10000, // Flush interval in ms (default: 10000)
retentionDays: 7, // Log retention days (default: 7)
},
aws: {
accessKeyId: 'YOUR_KEY', // Optional: For local dev
secretAccessKey: 'YOUR_SECRET', // Optional: For local dev
},
})Environment-Based Configuration
appsettings.json (Production):
{
"Serilog": {
"MinimumLevel": {
"Default": "Information"
}
},
"RequestLogging": {
"UseCloudWatch": true,
"UseConsole": false,
"LogGroupName": "/ecs/my-app-requests"
}
}appsettings.local.json (Local):
{
"RequestLogging": {
"UseCloudWatch": false,
"UseConsole": true
}
}Output Format
The package produces Serilog Compact JSON format compatible with .NET applications:
{
"@t": "2025-12-23T09:30:42.8545093Z",
"@mt": "HTTP {RequestMethod} {EndpointName} responded {StatusCode} in {Elapsed:0.0000} ms",
"@l": "Information",
"@r": ["141.9576"],
"EndpointName": "api/users",
"RequestMethod": "GET",
"RequestPath": "/api/users",
"StatusCode": 200,
"Elapsed": 141.957558,
"SourceContext": "Serilog.AspNetCore.RequestLoggingMiddleware",
"RequestId": "ABC123XYZ456",
"ConnectionId": "127.0.0.1:00000001"
}Console Output Formats
Pretty (Development)
[10:30:42] info: HTTP GET /api/users responded 200 in 142ms
{
"StatusCode": 200,
"Elapsed": 141.96
}Serilog Template (.NET Style)
[10:30:42 INF] [RequestLogging] HTTP GET /api/users responded 200 in 141.9576 msJSON (Debug Format)
{"@t":"2025-12-23T10:30:42.854Z","@mt":"HTTP {RequestMethod} {EndpointName}..."}Advanced Usage
Custom Logger Instance
import { createWhLogger } from 'wh-log-track';
const logger = createWhLogger({
appName: 'custom-logger',
useConsole: true,
useCloudWatch: false,
});
logger.info('Custom log message', { userId: 123 });Async Configuration (NestJS)
WhLogTrackModule.forRootAsync({
inject: [ConfigService],
useFactory: async (config: ConfigService) => ({
appName: config.get('APP_NAME'),
useCloudWatch: config.get('USE_CLOUDWATCH'),
useConsole: config.get('USE_CONSOLE'),
}),
})AWS IAM Permissions
For CloudWatch logging, ensure your IAM role has these permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogStreams"
],
"Resource": "arn:aws:logs:*:*:log-group:/ecs/*"
}
]
}Migration from .NET Serilog
This package is designed to match .NET Serilog behavior:
| .NET Feature | Node.js Equivalent |
|--------------|-------------------|
| UseSerilogRequestLogging() | whLogMiddleware() (Express) or WhRequestLoggingInterceptor (NestJS) |
| AmazonCloudWatch sink | winston-cloudwatch with Serilog formatter |
| CompactJsonFormatter | serilogCompactFormatter |
| LogEventLevel.Information | info level mapped to Information |
License
MIT
Support
For issues and questions, please open an issue on GitHub.
