Log levels
- Node.js course
- Advanced
- Lesson 62/83
- 5 min
Learn log levels (error, warn, info, debug).
Log levels
Log levels indicate the importance of a log. Winston's default levels (in order of importance): error, warn, info, http, verbose, debug, silly. error is the highest, silly the lowest priority.
The logger's level setting sets a threshold: only this level and above are written. Example: level: "info" writes info, warn and error logs; it skips debug and silly. Production usually uses info, development uses debug. This way you see detailed logs in development, and only important logs remain in production. A separate transport can be set per level: error logs to a file, info to the console.
Error and warn logs
Use logger.error(...) for errors and logger.warn(...) for warnings. Error logs are usually written to a separate file, since they are used for diagnosis.
Example: logger.error("Database connection failed"); logger.warn("Memory usage is high");. error is a critical problem; warn is noteworthy but does not block the system. Winston can use a different file per level: new winston.transports.File({ filename: "error.log", level: "error" }). This way errors collect in error.log, general logs in app.log. This separation speeds up diagnosis. In production error logs can also be routed to an alert system.
Practice Write an info log
Import the winston module. Create a logger with winston.createLogger({ level: "info", transports: [new winston.transports.Console()] }). Log with logger.info("Running").
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",
transports: [new winston.transports.Console()]
});
logger.info("Running");Expected output
Running
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the info log call
logger.____("Server started");
logger.info("Server started");
Explanation: logger.info logs information.
2 Match each level to its meaning
| Term | Meaning |
|---|---|
error |
Critical error |
warn |
Warning |
info |
Information |
debug |
Debugging |
3 Which level has the highest priority?
logger.error('...')- debug
- error Correct answer
- info
- silly
Explanation: error is the highest priority level.