elegant-logger
v1.0.1
Published
A professional, beautiful, and highly customizable Express request and error logger middleware for Node.js services.
Maintainers
Readme
elegant-logs
A professional, beautiful, and highly customizable Express request and error logger middleware for Node.js services.
Features
- 🎨 Colorized Terminal Output: Beautifully structured logs with ANSI colors based on HTTP method, response time, and status codes.
- 🔒 Auto-Redaction: Automatically redacts sensitive fields from request bodies (e.g.,
password,token,secret,apiKey,authorization). - ⚡ Precision Timing: High-resolution response timers formatted with appropriate units (e.g., microseconds
μs, millisecondsms, or secondss). - ⚙️ Customizable Log Content: Optionally include or skip request body, query parameters, or HTTP headers.
- 🛠️ Custom Loggers: Easily hook into your log stream (e.g., to send structured logs to Datadog, Logstash, or Sentry).
- 🐛 Elegant Error Logging: Standardized middleware to print clean error stack traces in development.
- 📦 Zero-Configuration Bundling: Pre-packaged as both ES Module (ESM) and CommonJS (CJS) with full TypeScript definitions.
Installation
Install via your preferred package manager:
# Using npm
npm install elegant-logs
# Using pnpm
pnpm add elegant-logs
# Using yarn
yarn add elegant-logsNote: Since elegant-logs is designed specifically for Express apps, make sure you have express installed in your project.
Getting Started
1. Request Logger Middleware
Import and use the middleware in your Express application:
import express from 'express';
import { loggerMiddleware } from 'elegant-logs';
const app = express();
app.use(express.json());
// Apply logger middleware
app.use(loggerMiddleware({
includeBody: true, // Log request body (defaults to true)
includeQuery: true, // Log query parameters (defaults to true)
includeHeaders: false // Log headers (defaults to false)
}));
app.get('/api/users', (req, res) => {
res.json({ ok: true });
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});2. Error Logger Middleware
Add the error logger middleware after all of your application routes:
import { errorLoggerMiddleware } from 'elegant-logs';
// ... your routes here ...
// Apply error logger
app.use(errorLoggerMiddleware);Options
loggerMiddleware accepts an optional configuration object of type LoggerOptions:
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| skip | (req, res) => boolean | undefined | A function to determine if a specific request should skip logging. |
| includeBody | boolean | true | When true, logs the JSON request body (redacting sensitive fields). |
| includeQuery | boolean | true | When true, logs the request query parameters. |
| includeHeaders | boolean | false | When true, logs the request headers. |
| customLogger | (logData: LogData) => void | undefined | A custom function to handle raw structured log objects (disables default console printing). |
Custom Logger Example
If you want to send logs to an external service or a filesytem logger:
app.use(loggerMiddleware({
customLogger: (logData) => {
// Send structured data to external metrics/log store
myTelemetryClient.send(logData);
}
}));Log Data Schema
When using customLogger, your function receives a LogData object with the following schema:
interface LogData {
timestamp: string; // ISO format string (YYYY-MM-DD HH:mm:ss)
method: string; // HTTP Method (GET, POST, etc.)
url: string; // The request URL path
statusCode: number; // The response status code
responseTime: number; // Response duration in milliseconds
clientIP: string; // Client IP address (considers X-Forwarded-For)
userAgent?: string; // The browser or client user agent header
body?: unknown; // The request body (sanitized)
query?: unknown; // The request query params
headers?: unknown; // The request headers
}License
ISC License (see LICENSE or package details).
