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…
Section overview
5 resourcesCovers 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
- Modify the logger to log to a different file based on the log level.
- Create more complex routes and log different information about the requests and responses.
- Handle unhandled promise rejections and log them using Winston.
Solutions
- 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()
]
});
-
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.
-
To handle unhandled promise rejections, you can listen for the
unhandledRejectionevent 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article