Winston
- Node.js course
- Advanced
- Lesson 61/83
- 5 min
Learn configurable logging with Winston.
What is Winston?
Winston is the most popular logging library for Node.js. Beyond console output, it offers file writing, log levels, timestamps and formatting. It is almost the standard in production systems.
Winston is not built in; you install it with npm install winston. Then you import it with const winston = require("winston"); and create a logger with winston.createLogger({ ... }). console.log is simple and temporary; Winston is durable, configurable and leveled. In production you want logs to go to a file, syslog or a central log server. Winston's transports concept decides where logs go: console, file, HTTP endpoint. In this group you will learn the core tools of Winston.
Creating a logger with createLogger
In Winston you create a logger with winston.createLogger({ ... }). The configuration includes log levels, format and transports. In its simplest form you provide just level and transports.
Example: const logger = winston.createLogger({ level: "info", transports: [new winston.transports.Console()] });. This logger writes info and above to the console. You log with logger.info("Server started"). Winston's default levels are: error, warn, info, http, verbose, debug, silly. The level setting decides which level and above are written. Winston allows separate configuration for production and development.
Practice Import Winston
Import the winston module with require. Print "Winston ready" with console.log.
Starter code
// Import the winston module
// write here
// Print "Winston ready"
// write hereSample solution
const winston = require("winston");
console.log("Winston ready");Expected output
Winston ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is Winston imported?
const winston = require("winston")- const winston = require("winston") Correct answer
- import winston from "log"
- const winston = new Winston()
- const winston = require("console")
Explanation: Winston is imported with require('winston').
2 Complete the createLogger call
const logger = winston.____({ level: "info" });
const logger = winston.createLogger({ level: "info" });
Explanation: winston.createLogger creates a logger.
3 Match each piece to its role
| Term | Meaning |
|---|---|
winston |
Library |
createLogger |
Creates a logger |
logger.info |
Logs info |
transports |
Log destinations |