changelog-utils-structured-logger
v1.0.1
Published
Validated logger utilities with trace IDs, rate limiting, and structured output.
Maintainers
Readme
changelog-utils-structured-logger
Validated logger utilities with trace IDs, rate limiting, and structured output.
Installation
npm install changelog-utils-structured-loggerQuick Start
import logger from "changelog-utils-structured-logger";
logger.info("Application started");
logger.debug("Debug data", { userId: 1 });
logger.warn("Deprecation notice");
logger.error("Something failed", new Error(" details"));Features
- Input validation — Message type checking, length limits, argument validation
- Sanitization — Redacts passwords, secrets, tokens, and card numbers
- Trace IDs — Correlation IDs for distributed logging
- Rate limiting — Configurable burst limits to prevent log spam
- Structured output — JSON mode for log aggregation (e.g. ELK)
- Child loggers — Prefix and trace-scoped loggers
- Timers —
startTimer,endTimer,measureAsyncfor performance logging - Log capture — Capture logs for testing assertions
API
Logger
Default export
import logger from "changelog-utils-structured-logger";
logger.trace(message: string, ...args: unknown[]): void
logger.debug(message: string, ...args: unknown[]): void
logger.info(message: string, ...args: unknown[]): void
logger.warn(message: string, ...args: unknown[]): void
logger.error(message: string, ...args: unknown[]): void
logger.fatal(message: string, ...args: unknown[]): void
logger.log(level: LogLevel, message: string, ...args: unknown[]): voidFactory & configuration
import { createLogger, getLogger, ChangelogUtilsLoggerOptions } from "changelog-utils-structured-logger";
// Create a new logger with options
const log = createLogger({
prefix: "[MyApp]",
minLevel: "info",
rateLimitMs: 1000,
maxRateLimitBurst: 10,
structured: true,
traceId: "req-123",
});
// Get or create singleton
const log2 = getLogger({ prefix: "[Global]" });ChangelogUtilsLoggerOptions
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| prefix | string | "" | Prepended to all messages |
| suffix | string | "" | Appended to all messages |
| minLevel | LogLevel | "trace" | Minimum level to emit |
| sanitizePatterns | RegExp[] | Built-in | Patterns for redaction |
| rateLimitMs | number | 0 | Rate limit window (ms); 0 = disabled |
| maxRateLimitBurst | number | 100 | Max logs per window |
| structured | boolean | false | Output JSON lines |
| traceId | string | "" | Correlation ID for all logs |
Extended methods
// Child logger with extra prefix
const childLog = logger.child("[Auth]");
// Child logger with trace ID (auto-generated if omitted)
const tracedLog = logger.withTraceId();
const tracedLog2 = logger.withTraceId("custom-id");
// Conditional log
logger.when(process.env.DEBUG === "1", "debug", "Debug info");
// Group key-value pairs
logger.group("Config", { host: "localhost", port: 3000 });
// Batch log multiple messages
logger.batch("info", ["Line 1", "Line 2", "Line 3"]);
// Log table-like data
logger.table([{ id: 1, name: "a" }, { id: 2, name: "b" }]);Timer utilities
import { startTimer, endTimer, measureAsync, formatDuration } from "changelog-utils-structured-logger";
// Manual timer
startTimer("fetch");
await fetchData();
const ms = endTimer("fetch");
console.log(`Took ${formatDuration(ms)}`);
// Async wrapper with auto-log
const result = await measureAsync("api-call", () => fetch(url));Standalone utilities
import {
generateTraceId,
formatDuration,
parseDuration,
loadEnv,
loadEnvAndLog,
colorizeLevel,
stripColors,
type LogLevel,
} from "changelog-utils-structured-logger";
generateTraceId(21); // "V1StGXR8_Z5jdHi6B-myT"
formatDuration(1500); // "1.5s"
parseDuration("2m"); // 120000
loadEnv(); // Load .env, return parsed object
loadEnvAndLog(".env", (keys) => console.log("Loaded:", keys));
colorizeLevel("error"); // Chalk-red "ERROR"
stripColors("\x1b[31mred\x1b[0m"); // "red"Log capture (testing)
import {
enableLogCapture,
disableLogCapture,
getCapturedLogs,
getPlainCapturedLogs,
clearCapturedLogs,
} from "changelog-utils-structured-logger";
enableLogCapture();
logger.info("test message");
const logs = getCapturedLogs();
const plain = getPlainCapturedLogs(); // ANSI stripped
disableLogCapture();
clearCapturedLogs();TypeScript
The package ships with type definitions. No @types needed.
import logger, { LogLevel, ChangelogUtilsLoggerOptions, LogEntry } from "changelog-utils-structured-logger";License
ISC
