Log Levels in Node.js 🎯

beginner
15 min

Log Levels in Node.js 🎯

Welcome to this comprehensive guide on Log Levels in Node.js! In this tutorial, we'll dive deep into understanding the importance of log levels and learn how to effectively use them in your projects. Let's get started!

Understanding Log Levels 📝

Log levels are a way to categorize log messages based on their importance. They help developers track the events in their application, manage errors, and debug issues more efficiently. Node.js provides six built-in log levels:

  1. ** emergency** (0): Critical conditions. The application can't continue running.
  2. ** alert** (1): Important, but not critical conditions. The application may continue running, but users should be warned.
  3. ** critical** (2): Critical errors that impact the application's functionality.
  4. ** error** (3): Run-time errors that need to be addressed.
  5. ** warn** (4): Potential problems that might occur in the future.
  6. ** info** (5): Informational messages about the application's state.
  7. ** debug** (6): Detailed, low-level diagnostic logs.

Setting Up a Custom Logger 💡

To create a custom logger in Node.js, we'll use the winston library. It's a popular logging solution that supports multiple transports, log levels, and customizable formatting.

First, let's install it:

bash
npm install winston

Now, let's create a logger by writing a simple script:

javascript
// Import Winston const winston = require('winston'); // Define custom log levels winston.config.npm = false; winston.addColors({ emergency: 'red', alert: 'yellow', critical: 'red', error: 'red', warn: 'orange', info: 'green', debug: 'blue', }); // Create a custom logger const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.colorize(), winston.format.simple() ), transports: [ new winston.transports.Console(), ], }); // Log messages logger.emergency('This is an emergency message'); logger.alert('This is an alert message'); logger.critical('This is a critical error'); logger.error('This is an error'); logger.warn('This is a warning'); logger.info('This is an informational message'); logger.debug('This is a debug message');

Save this script as logger.js and run it using:

bash
node logger.js

You should see the log messages in your console with their respective colors.

Quick Quiz
Question 1 of 1

What is the purpose of log levels in Node.js?

Logging in Real-world Applications 💡

In real-world applications, it's essential to log messages at appropriate levels. Here's an example using the logger created earlier:

javascript
const express = require('express'); const app = express(); const logger = require('./logger'); // Log an informational message app.get('/', (req, res) => { logger.info('Home page loaded'); res.send('Welcome to CodeYourCraft'); }); // Log an error message app.get('/error', (req, res) => { throw new Error('This is a custom error'); }); // Catch and log errors app.use((err, req, res, next) => { logger.error(err.message); res.status(500).send('An error occurred'); }); app.listen(3000, () => { logger.info('Server started on port 3000'); });

In this example, we've created a simple Express app that logs informational and error messages using the custom logger we created earlier. The app catches errors and logs them using the error log level.

Quick Quiz
Question 1 of 1

Why is it essential to log messages at appropriate levels in real-world applications?

That's all for this comprehensive guide on Log Levels in Node.js! By now, you should have a good understanding of why log levels are important, how to set up a custom logger, and how to use log levels in real-world applications. Happy coding! 🤖