Mongoose Morgan Logger

1.0.17 · active · verified Wed Apr 22

mongoose-morgan is an npm package designed to integrate Express.js HTTP request logging (via morgan) directly into a MongoDB database (via mongoose). The current stable version is 1.0.17, which primarily focuses on updating dependencies to maintain compatibility and security. Historically, the package has seen irregular but focused feature additions, such as support for capped collections and improved handling of MongoDB Atlas connection strings. Its key differentiator is simplifying the process of persisting detailed HTTP access logs into a NoSQL database, offering configurable options for the target collection, user authentication, and advanced MongoDB connection parameters without requiring separate setup for both logging and database interaction. It's a pragmatic choice for Express applications already utilizing Mongoose for data persistence that need a straightforward way to store request logs.

Common errors

Warnings

Install

Imports

Quickstart

This example sets up an Express application to log all incoming HTTP requests to a MongoDB database using `mongoose-morgan`. It demonstrates basic usage with a connection string and two example routes to generate logs.

import express from 'express';
import morgan from 'mongoose-morgan';
import mongoose from 'mongoose';

const app = express();
const port = process.env.PORT || 8080;

// Ensure MongoDB connection for mongoose-morgan
// In a real app, you'd typically connect Mongoose once at app startup.
// For simplicity here, mongoose-morgan handles its own connection based on connectionString.

app.use(morgan({
    connectionString: process.env.MONGO_URI || 'mongodb://localhost:27017/logs-db'
}));

app.get('/', (req, res) => {
    res.send('Hello World! Check your MongoDB logs.');
});

app.get('/error', (req, res) => {
    res.status(500).send('An error occurred.');
});

// Close Mongoose connection on app shutdown (optional, but good practice)
process.on('SIGINT', async () => {
    await mongoose.disconnect();
    console.log('MongoDB connection disconnected through app termination');
    process.exit(0);
});

app.listen(port, () => {
    console.log(`Server running on port ${port}. Visit http://localhost:${port}`);
});

view raw JSON →