Home  Express   Morgan midd ...

morgan middleware in express

To use morgan middleware in an Express.js application, you typically install it via npm and then require it in your main application file (e.g., app.js or index.js). Here's a basic example of how you can set up morgan:

  1. Install morgan: First, install morgan using npm or yarn if you haven't already:

    npm install morgan
    
  2. Require and Use morgan in Your Express App:

    In your main application file (app.js or index.js), require morgan and use it as middleware:

    const express = require('express');
    const morgan = require('morgan');
    
    const app = express();
    
    // Use morgan middleware with 'dev' format
    app.use(morgan('dev'));
    
    // Define your routes and other middleware
    // Example route
    app.get('/', (req, res) => {
        res.send('Hello World!');
    });
    
    // Start the server
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });
    
  3. Explanation:

    • const morgan = require('morgan');: Import morgan into your application.
    • app.use(morgan('dev'));: Use morgan middleware with the 'dev' format. 'dev' is one of the pre-defined formats in morgan that gives you concise output colored by response status for development use.
    • You can replace 'dev' with other formats like 'combined', 'common', or create custom formats as per your logging needs. For example:
      app.use(morgan('combined'));
      
      This format provides more detailed logging information.
  4. Start Your Server: Finally, start your Express server using app.listen() as shown in the example.

When you run your Express application after setting up morgan middleware, you'll see HTTP request details (like method, URL, status code, response time, etc.) logged to the console, which is helpful for debugging and monitoring your application's requests.

Published on: Jun 29, 2024, 03:13 PM  
 

Comments

Add your comment