File Rotation
Overview
Section titled “Overview”The FileTransport writes NDJSON (one JSON entry per line) to daily rotating log files using Node.js fs.createWriteStream in append mode. It is entirely non-blocking.
logs/├── 2024-05-12.log ← auto-pruned├── 2024-05-13.log ← auto-pruned├── 2024-05-14.log└── 2024-05-15.log ← active WriteStreamBasic setup
Section titled “Basic setup”import { Wiz } from "@gouranga_samrat/log-wiz";
const logger = new Wiz({ file: { dir: "./logs", maxFiles: 7, },});log-wiz creates ./logs/ if it doesn’t exist, and starts writing to YYYY-MM-DD.log.
Async buffer
Section titled “Async buffer”For high-throughput applications, enable the async buffer to batch writes:
const logger = new Wiz({ file: { dir: "./logs", maxFiles: 14, asyncBuffer: true, // batch writes (default: true) bufferSize: 200, // flush every 200 entries… flushIntervalMs: 500, // …or every 500 ms, whichever comes first },});With async buffering, the event loop is never blocked by disk I/O. A timer (setInterval) is used internally with unref() so it doesn’t prevent process exit.
Day rollover
Section titled “Day rollover”At midnight, log-wiz automatically:
- Flushes the current buffer to the old file
- Closes the active
WriteStream - Opens a new
WriteStreamfor the new date - Prunes files exceeding
maxFiles
No entries are lost during rollover.
Retention and pruning
Section titled “Retention and pruning”Files are pruned by date sort — the oldest files are deleted first. Only files matching the YYYY-MM-DD.log pattern in the configured dir are considered.
// Keep 30 days of logsconst logger = new Wiz({ file: { dir: "./logs", maxFiles: 30 },});Graceful shutdown
Section titled “Graceful shutdown”Always flush and close before your process exits:
// Handle all termination signalsfor (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) { process.on(signal, async () => { logger.flush(); // synchronous drain await logger.close(); // close WriteStream process.exit(0); });}
// Also handle uncaught errorsprocess.on("uncaughtException", async (err) => { logger.fatal("Uncaught exception", { error: err }); await logger.close(); process.exit(1);});Disabling file output
Section titled “Disabling file output”// Console only — no file transportconst logger = new Wiz({ file: false });Multiple directories
Section titled “Multiple directories”Create separate instances with different dir settings:
const appLogger = new Wiz({ scope: "app", file: { dir: "./logs/app", maxFiles: 7 },});
const auditLogger = new Wiz({ scope: "audit", format: "json", file: { dir: "./logs/audit", maxFiles: 90 }, // keep 3 months});