Node.js
Winston
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.
Exercise Import Winston
Import the winston module with require. Print "Winston ready" with console.log.
Show example solution
const winston = require("winston");
console.log("Winston ready");
Test yourself
-
How is Winston imported?
const winston = require("winston")
- const winston = require("winston")
- import winston from "log"
- const winston = new Winston()
- const winston = require("console")
Show answer
const winston = require("winston") — Winston is imported with require('winston').
-
Complete the createLogger call
const logger = winston.____({ level: "info" });
Show answer
const logger = winston.createLogger({ level: "info" });
-
Match each piece to its role
- winston
- Library
- createLogger
- Creates a logger
- logger.info
- Logs info
- transports
- Log destinations
Next lesson: Log levels