Node.js
Transports
Learn output targets with Winston transports.
Transports
A transport decides where logs go. Winston's common transports: Console (to the console), File (to a file), Http (to an HTTP endpoint). You can add multiple transports to a logger.
Example: transports: [new winston.transports.Console(), new winston.transports.File({ filename: "app.log" })]. This writes logs to both the console and the app.log file. Transports are independent; each can have its own filter and format. In production you may want to send logs to a central server; an HTTP transport does that. Winston also allows writing custom transports. The transport concept is the basis of Winston's flexibility; with one logger you send logs to multiple destinations.
The File transport
The File transport writes logs to a file. The filename property sets the file name, the level property sets which level is written. In production log files are bounded by rotation.
Example: new winston.transports.File({ filename: "app.log", level: "info" }). This transport writes info and above to the app.log file. maxsize sets a file size limit, maxFiles sets a file count limit. The winston-daily-rotate-file plugin does daily rotation. In production log files grow fast; without rotation the disk fills up. With multiple transports you can keep error logs and info logs in separate files. This speeds up log search.
Exercise Create a logger with a File transport
Import the winston module. Create a logger with winston.createLogger({ level: "info", transports: [new winston.transports.File({ filename: "app.log" })] }). Write logger.info("Saved").
Show example solution
const winston = require("winston");
const logger = winston.createLogger({
level: "info",
transports: [new winston.transports.File({ filename: "app.log" })]
});
logger.info("Saved");
Test yourself
-
Match each transport to its target
- Console
- Writes to console
- File
- Writes to a file
- Http
- Writes to an HTTP endpoint
- transports
- Transport list
-
Which property gives the file name to the File transport?
new winston.transports.File({ filename: "app.log" })
Show answer
filename — filename sets the file name.
-
Complete the File transport call
new winston.transports.File({ filename: "____" })
Show answer
new winston.transports.File({ filename: "app.log" })
Next lesson: Structured logging