Express.js / Error Handling in Express.js

Logging Errors with Winston and Morgan

In this tutorial, you'll learn how to log errors with Winston and Morgan, two popular logging libraries for Express.js. Proper logging is crucial for understanding and debugging y…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers error handling strategies and best practices for Express applications.

1. Introduction

Goal of the Tutorial

In this tutorial, we aim to understand how to log errors with Winston and Morgan, two highly used logging libraries in Express.js. Logging errors is a significant part of any application as it helps in debugging and maintaining the application.

What will you learn?

  • Introduction to Winston and Morgan libraries.
  • Integrating Winston and Morgan into the Express.js application.
  • Logging errors using Winston and Morgan.

Prerequisites

  • Basic understanding of Node.js and Express.js.
  • Node and npm installed on your system.
  • A text editor such as Visual Studio Code.

2. Step-by-Step Guide

Introduction to Winston and Morgan

Winston is a versatile logging library for Node.js. It is designed to be a simple and universal logging library with support for multiple transports. A transport is essentially a storage device for your logs.

Morgan is another HTTP request logger middleware for Node.js. It simplifies the process of logging requests to your application.

Installing Winston and Morgan

To install Winston and Morgan, run the following command in your terminal:

npm install winston morgan

Logging Errors Using Winston and Morgan

We will create an Express application and integrate Winston and Morgan into it for logging.

3. Code Examples

Creating an Express Application

// Importing express module
const express = require('express');

// Creating express application
const app = express();

// A simple GET route
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// Starting the server
app.listen(3000, () => {
  console.log('Server is running at http://localhost:3000');
});

Integrating Winston and Morgan

// Importing required modules
const express = require('express');
const winston = require('winston');
const morgan = require('morgan');

// Creating express application
const app = express();

// Creating new Winston logger
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.Console()
  ]
});

// Using morgan middleware for logging
app.use(morgan('combined', { stream: { write: message => logger.info(message.trim()) } }));

// A simple GET route
app.get('/', (req, res) => {
  res.send('Hello World!');
  throw new Error('This is an error');
});

// Error handling middleware
app.use((err, req, res, next) => {
  logger.error(err.message);
  res.status(500).send('Something went wrong!');
});

// Starting the server
app.listen(3000, () => {
  console.log('Server is running at http://localhost:3000');
});

4. Summary

We have learned about the Winston and Morgan logging libraries and how to integrate them into an Express.js application. Furthermore, we have learned how to log errors using these libraries.

To delve deeper into these libraries, you can visit their official documentation: Winston and Morgan.

5. Practice Exercises

  1. Modify the logger to log to a different file based on the log level.
  2. Create more complex routes and log different information about the requests and responses.
  3. Handle unhandled promise rejections and log them using Winston.

Solutions

  1. To log to different files based on the log level, we can add multiple transports with different filenames and levels.
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'info.log', level: 'info' }),
    new winston.transports.Console()
  ]
});
  1. To log different information about the requests and responses, you can modify the string passed to the morgan function. See the Morgan documentation for more details.

  2. To handle unhandled promise rejections, you can listen for the unhandledRejection event on the process object.

process.on('unhandledRejection', (reason, promise) => {
  logger.error('Unhandled Promise Rejection: ', reason);
});

Remember that practice is key when learning new concepts. Keep experimenting with different scenarios and configurations to get a better understanding of Winston and Morgan.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help