1.0.1 âĸ Published 7 months ago
@codephil/logging-middleware-ddog v1.0.1
@codephil/logging-middleware-ddog
Express middleware for structured logging to Datadog with pretty console output. Sends logs directly to Datadog's HTTP intake API without requiring the Datadog Agent.
Features
- đ Direct logging to Datadog via HTTP API
- đ Pretty console output for local development
- đ Automatic HTTP request/response logging
- ⥠Performance monitoring with memory usage
- đ¯ TypeScript type definitions included
- đ Express middleware compatible
Installation
npm install @codephil/logging-middleware-ddog
Usage
const express = require('express');
const { datadogMiddleware } = require('@codephil/logging-middleware-ddog');
const app = express();
// Initialize the middleware
app.use(datadogMiddleware({
serviceName: 'your-service-name', // Optional if set in env
apiKey: 'your-datadog-api-key', // Optional if set in env
nodeEnv: 'development', // Optional if set in env
warnThreshold: 1000, // Response time warning threshold (ms)
errorThreshold: 3000 // Response time error threshold (ms)
}));
// Use the logger in your routes
app.get('/api/users', (req, res) => {
req.logger.info('Fetching users', {
additional: 'context',
userId: req.user?.id
});
// ... your route logic
});
Environment Variables
The middleware will look for these environment variables if not provided in options:
DD_API_KEY
: Your Datadog API keySERVICE_NAME
: Your service nameNODE_ENV
: Environment (development, production, etc.)
Options
interface DatadogOptions {
apiKey?: string; // Datadog API key
serviceName?: string; // Service name for Datadog
nodeEnv?: string; // Environment (development, production, etc.)
logLevel?: string; // Winston log level
warnThreshold?: number; // Response time warning threshold in ms (default: 1000)
errorThreshold?: number; // Response time error threshold in ms (default: 3000)
}
Console Output
The middleware provides pretty console output for local development:
12:34:56 âšī¸ info: GET /api/users
â GET /api/users
â 200 (45ms)
⥠Performance: 45ms | Memory: 2.5MB
12:34:57 â ī¸ warn: Slow request detected
â GET /api/tasks
â 200 (1250ms)
⥠Performance: 1250ms | Memory: 5.8MB
Status codes are color-coded:
- 2xx: Green (success)
- 3xx: Cyan (redirect)
- 4xx: Yellow (client error)
- 5xx: Red (server error)
Performance metrics are automatically tracked:
- Response time warnings when exceeding thresholds
- Memory usage per request
- Color-coded performance indicators
Datadog Integration
Logs are sent directly to Datadog's HTTP intake API with the following structure:
{
message: "HTTP Request Completed",
level: "info",
ddsource: "nodejs",
service: "your-service-name",
http: {
method: "GET",
url: "/api/users",
status_code: 200,
response_time_ms: 45
},
performance: {
responseTime: 45,
memoryUsed: 2621440, // in bytes
route: "/api/users"
},
// ... additional context
}