Transports
- Node.js course
- Advanced
- Lesson 63/83
- 5 min
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.
Practice 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").
Starter code
// Import winston
// write here
// Create a logger with a File transport
// write here
// Write an info log
// write hereSample solution
const winston = require("winston");
const logger = winston.createLogger({
level: "info",
transports: [new winston.transports.File({ filename: "app.log" })]
});
logger.info("Saved");Expected output
Saved
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each transport to its target
| Term | Meaning |
|---|---|
Console |
Writes to console |
File |
Writes to a file |
Http |
Writes to an HTTP endpoint |
transports |
Transport list |
2 Which property gives the file name to the File transport?
new winston.transports.File({ filename: "app.log" })- path
- file
- name
- filename Correct answer
Explanation: filename sets the file name.
3 Complete the File transport call
new winston.transports.File({ filename: "____" })
new winston.transports.File({ filename: "app.log" })
Explanation: Write new winston.transports.File({ filename: "app.log" }).