Node.js
Summary - Logging
Combine Winston, levels and structured to write a log system.
Summary - Logging
In this group you learned the core tools of logging in Node.js: creating a logger with winston.createLogger, setting priority with log levels (error, warn, info), writing logs to different destinations with transports, using format.json() for structured logging, and meeting Pino for high performance.
Now you will combine these into a small logger skeleton. The skeleton will write logs in JSON format to both the console and a file. This mini task shows how the logging tools combine.
Logger design
A production logger skeleton is this: a logger with createLogger, both console and file destinations with transports, JSON format with format.json. The threshold is set with level: "info".
Flow: const logger = winston.createLogger({ level: "info", format: winston.format.json(), transports: [new winston.transports.Console(), new winston.transports.File({ filename: "app.log" })] });. This logger writes each log as JSON to the console and to app.log. In production you can add a separate file for error level and another for info. On top of this skeleton you can add timestamps, log rotation and central log server shipping.
Exercise Build the production logger skeleton
Import winston. Create a logger with winston.createLogger({ level: "info", format: winston.format.json(), transports: [new winston.transports.Console(), new winston.transports.File({ filename: "app.log" })] }). Write logger.info("System ready").
Show example solution
const winston = require("winston");
const logger = winston.createLogger({
level: "info",
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: "app.log" })
]
});
logger.info("System ready");
Test yourself
-
What pieces does the logger skeleton combine?
createLogger + transports + format.json
- Only require
- createLogger, transports and format.json
- Only console.log
- Only info
Show answer
createLogger, transports and format.json — createLogger + transports + format.json combine.
-
Match each tool to its role
- createLogger
- Creates a logger
- transports
- Sets destinations
- format.json
- Sets JSON format
- logger.info
- Logs info
Next lesson: dotenv