Rotate Logs Daily with Winston
How to configure daily log rotation in Node.js using winston and winston-daily-rotate-file: size limits, retention, compression, and multiple transports.
Overview
A Node service that logs to a file keeps appending until the disk fills, and then you’re SSHing into production at 2am to delete a 40GB app.log. The winston-daily-rotate-file transport for Winston writes logs to date-stamped files that rotate on a schedule (or when they hit a size cap), compresses the old ones, and deletes anything past your retention window. This recipe covers the full setup: basic rotation, split info/error files, gzip archiving, rotation events, Express integration via morgan, and shipping rotated files to S3.
When to Use
- Applications that write logs to files (not just stdout) and need rotation
- Environments where a log collector (Fluent Bit, Filebeat) isn’t available
- Long-running services where unbounded log growth would fill the disk
- Compliance requirements that mandate keeping logs for N days then deleting them
When NOT to Use
- Containerized applications: write JSON to stdout and let the orchestrator handle rotation; Docker, Kubernetes, and systemd already do this job.
- High-throughput logging: pino writing to stdout is much faster than Winston with file transports; file I/O on every event adds latency.
- Short-lived scripts: a single log file or plain
console.logis enough when the process exits in minutes.
Solution
Setup
npm install winston winston-daily-rotate-file
Basic daily rotation
The minimal config: a filename with the %DATE% placeholder, a rotation schedule, a size cap, and a retention window.
import winston from "winston";
import DailyRotateFile from "winston-daily-rotate-file";
const logger = winston.createLogger({
level: "info",
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json(),
),
transports: [
new DailyRotateFile({
filename: "logs/application-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "14d",
}),
],
});
logger.info("server_started", { port: 3000 });
logger.warn("cache_miss", { key: "user:42" });
logger.error("database_error", { error: "Connection refused" });
This creates files like logs/application-2026-07-05.log, rotates daily, caps each file at 20MB, and keeps 14 days of logs. When either condition triggers (a new day or a file over 20MB), the current file is closed, renamed with its date stamp, and a fresh one opens.
Separate error log file
Two transports with different level filters give you an error file that’s easy to alert on. Note that error entries land in both files: the error transport sees everything the info transport does plus nothing else.
const logger = winston.createLogger({
level: "info",
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json(),
),
transports: [
new DailyRotateFile({
filename: "logs/application-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "14d",
level: "info",
}),
new DailyRotateFile({
filename: "logs/error-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "30d",
level: "error",
}),
],
});
logger.info("goes_to_application_log");
logger.error("goes_to_both_logs");
Keeping errors for 30d while general logs age out at 14d is a common pattern. You want the error trail around longer.
Adding console output in development
File transports make development painful (you end up tail -fing a file). Gate the console transport behind NODE_ENV:
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || "info",
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json(),
),
transports: [
new DailyRotateFile({
filename: "logs/application-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "14d",
}),
],
});
if (process.env.NODE_ENV !== "production") {
logger.add(
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple(),
),
}),
);
}
Zipped archive rotation
zippedArchive: true gzips each rotated file; uncompressed text logs typically shrink to 10-20% of their original size. The auditFile records which files exist and their sizes; Winston reads it on startup to resume rotation state after a restart.
const transport = new DailyRotateFile({
filename: "logs/application-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "30d",
zippedArchive: true,
auditFile: "logs/audit.json",
});
const logger = winston.createLogger({
transports: [transport],
});
Custom log format
winston.format.printf gives you full control over the output shape. Pair it with format.errors({ stack: true }) so Error objects serialize with their stack instead of as {}.
const logFormat = winston.format.printf(({ timestamp, level, message, ...meta }) => {
return JSON.stringify({
timestamp,
level,
message,
...meta,
});
});
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
logFormat,
),
transports: [
new DailyRotateFile({
filename: "logs/application-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "14d",
}),
],
});
logger.error("something_failed", { error: new Error("boom") });
// Output: {"timestamp":"2026-07-05T10:30:00Z","level":"error","message":"something_failed","error":{"stack":"..."}}
Handling rotation events
The transport emits events at each lifecycle point, handy for alerting, uploading archives, or auditing.
const transport = new DailyRotateFile({
filename: "logs/application-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "14d",
});
transport.on("rotate", (oldFilename, newFilename) => {
console.log(`Log rotated from ${oldFilename} to ${newFilename}`);
});
transport.on("archive", (zipFilename) => {
console.log(`Log archived to ${zipFilename}`);
});
transport.on("logRemoved", (removedFilename) => {
console.log(`Old log removed: ${removedFilename}`);
});
const logger = winston.createLogger({ transports: [transport] });
rotate fires when a file is closed and renamed, archive when it’s gzipped, and logRemoved when retention deletes it. All three run after the fact, so your log writes don’t block on them.
Size-based rotation without daily naming
If you care about size more than calendar days, shrink the datePattern granularity or drop %DATE% from the filename entirely. Here files rotate at 10MB and only the last 5 survive.
const transport = new DailyRotateFile({
filename: "logs/application.log",
maxSize: "10m",
maxFiles: 5,
datePattern: "YYYY-MM-DD-HH",
});
const logger = winston.createLogger({ transports: [transport] });
A numeric maxFiles (instead of "14d") keeps exactly that many files, which is simpler to reason about when retention is counted in pieces, not days.
Integration with Express
Pipe morgan’s request log into Winston so HTTP access logs rotate with everything else:
import express from "express";
import winston from "winston";
import DailyRotateFile from "winston-daily-rotate-file";
import morgan from "morgan";
const logger = winston.createLogger({
level: "info",
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json(),
),
transports: [
new DailyRotateFile({
filename: "logs/access-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "14d",
}),
new DailyRotateFile({
filename: "logs/error-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "30d",
level: "error",
}),
],
});
const app = express();
const stream = { write: (msg) => logger.info(msg.trim()) };
app.use(morgan("combined", { stream }));
app.get("/api/users/:id", (req, res) => {
logger.info("user_fetched", { user_id: req.params.id });
res.json({ id: req.params.id, name: "Alice" });
});
app.listen(3000);
Explanation
The rotation lifecycle has four stages. Winston writes to the active file until a trigger fires: midnight rolls the datePattern over, or the file passes maxSize. At that point the transport closes the file, renames it with the resolved date stamp (that’s what %DATE% is for), opens a new active file, and emits rotate. If zippedArchive is on, the renamed file gets gzipped and archive fires. Finally, the retention sweep deletes anything outside maxFiles and emits logRemoved.
Three details that aren’t obvious from the options table:
%DATE%resolves per file. Two size-triggered rotations on the same day produceapplication-2026-11-23.logandapplication-2026-11-23-1.log. The counter suffix prevents collisions.auditFilesurvives restarts. Without it, a restarted process doesn’t know which files already exist, so retention counting starts fresh and old files can linger. Keep the audit file next to the logs and back it up with them.- Rotation is per process. Two app instances writing to the same
logs/directory will race: each has its own open file handle and its own idea of rotation state. Give each instance its own filename pattern (e.g., include the hostname or pod name) or route to a shared collector instead.
Variants
Using Winston with TypeScript
import winston from "winston";
import DailyRotateFile from "winston-daily-rotate-file";
const logger = winston.createLogger({
level: "info",
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json(),
),
transports: [
new DailyRotateFile({
filename: "logs/application-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "14d",
}),
],
});
interface LogMetadata {
user_id?: number;
request_id?: string;
duration_ms?: number;
}
function logInfo(message: string, meta: LogMetadata = {}): void {
logger.info(message, meta);
}
Combining with Sentry transport
Fan out errors to Sentry while files handle the full stream:
import * as Sentry from "@sentry/node";
import winston from "winston";
import DailyRotateFile from "winston-daily-rotate-file";
Sentry.init({ dsn: process.env.SENTRY_DSN });
const sentryTransport = new winston.transports.Stream({
stream: {
write: (message) => {
const logEntry = JSON.parse(message);
if (logEntry.level === "error") {
Sentry.captureException(new Error(logEntry.message));
}
},
},
});
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json(),
),
transports: [
new DailyRotateFile({
filename: "logs/application-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxSize: "20m",
maxFiles: "14d",
}),
sentryTransport,
],
});
A runnable version of this setup (logger config + Express server with morgan) is in the companion repository.
Best Practices
- Use
zippedArchive: truefor anything kept longer than a week; the disk savings are significant on text logs. - Prefer duration retention (
maxFiles: "14d") over counts (maxFiles: 5) when compliance says “keep 30 days of logs”, since it’s harder to get wrong. - Set
maxSizeso a single day can’t run away; 20MB is a sane default for medium-traffic APIs. - Split error and info into separate transports: errors deserve a longer retention window and a file you can
tailduring an incident. - Keep the console transport out of production; file I/O plus console I/O doubles the write cost per event.
- Emit JSON (
winston.format.json()or aprintfJSON line) so log aggregators parse it reliably, unlike free text. - Set
auditFileexplicitly inside your logs directory so rotation state survives deploys and restarts.
Common Mistakes
- Not setting
maxFiles. Without a retention cap, old files accumulate until the disk fills. Rotation without retention only delays the same incident. maxSizetoo small. Files rotate every few minutes, flooding the directory with fragments and making the audit file churn. Start at 20MB and adjust from real volume.- Two instances sharing one log directory. Each process rotates independently and they’ll clobber each other’s files. Include the hostname/pod name in the filename.
- Logging files in containers. Stdout to the orchestrator is the right channel; a container’s filesystem is ephemeral anyway.
- Ignoring the
auditFile. Deleting it (or pointing it outside the log dir) loses retention history on every restart.
Further Reading
- winston documentation — transports, formats, and levels
- winston-daily-rotate-file — all rotation options and events
- Node.js logging guide — stdout vs file logging fundamentals
Frequently Asked Questions
What is the difference between maxFiles as a number vs a string?
A number (maxFiles: 5) keeps exactly 5 files. A string with duration (maxFiles: "14d") keeps files from the last 14 days. Use duration strings for time-based retention and numbers when you're counting pieces.
How do I change the timezone of the date in the filename?
Winston uses the system timezone for datePattern. For UTC filenames, run the process with TZ=UTC in the environment rather than trying to format it in code.
Can I rotate by hour instead of day?
Yes. Add the hour to datePattern:
new DailyRotateFile({
filename: "logs/application-%DATE%.log",
datePattern: "YYYY-MM-DD-HH",
maxSize: "100m",
maxFiles: "7d",
});
Useful when a single day produces more data than one file should hold.
How do I ship rotated files to S3?
Hook the archive event. It fires right after a file is gzipped, which is exactly what you want to upload:
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import fs from "fs";
import path from "path";
const s3 = new S3Client({});
transport.on("archive", async (zipFilename) => {
await s3.send(new PutObjectCommand({
Bucket: "my-logs",
Key: `logs/${path.basename(zipFilename)}`,
Body: fs.readFileSync(zipFilename),
}));
});
Handle the promise rejection: a failed upload shouldn't take down your logger.
Should I use Winston or pino for file logging?
Use pino when raw throughput matters; it's several times faster and its pino/file transport writes to disk with far less overhead. Use Winston when you need multiple transports with different levels and formats, or want rotation handled inside the logger instead of by a separate tool like logrotate. For a deeper comparison, see High-Performance Logging with pino.
Related Resources
High-Performance Logging with pino
How to use pino for fast structured JSON logging in Node.js, including log levels, child loggers, transports, and integration with Express and Fastify.
RecipeError Tracking with Sentry in Express
How to integrate Sentry for error tracking in Node.js Express apps with the v8+ SDK — error handlers, performance spans, release tracking and source maps.
RecipeStructured JSON Logging with structlog
How to emit structured JSON logs in Python using structlog, including context binding, log levels, processors, and integration with standard logging.
RecipeStructured Logging: JSON Logs with Correlation IDs
Implement structured logging with JSON output, correlation IDs, and log aggregation for production observability.
RecipeProduction Logging in Python, JavaScript and Java
Implement structured, level-based logging with correlation IDs and secret redaction in Python, JavaScript, and Java.