Summary - Logging
- Node.js course
- Advanced
- Lesson 66/83
- 5 min
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.
Practice 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").
Starter code
// Import winston and create a logger
// write here
// Write an info log
// write hereSample 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");Expected output
System ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What pieces does the logger skeleton combine?
createLogger + transports + format.json- Only require
- createLogger, transports and format.json Correct answer
- Only console.log
- Only info
Explanation: createLogger + transports + format.json combine.
2 Match each tool to its role
| Term | Meaning |
|---|---|
createLogger |
Creates a logger |
transports |
Sets destinations |
format.json |
Sets JSON format |
logger.info |
Logs info |