In Node.js we can log errors to MongoDB.

To start with, let's install the mongoose driver:


npm install mongoose --save

Then we define the following document schema for our logs:


'use strict';

const mongoose  = require('mongoose');

const Schema  = mongoose.Schema;

const LogSchema = new Schema({
    time: Date,
    file: String,
    line: String,
    info: Mixed,
    type: String

},{collection: 'logs'});

module.exports = mongoose.model('logs', LogSchema);

Done this, we can define the following utility function:


'use strict';

const log = (data, logs) => {
    return new logs({
        time: new Date(),
        file: data.file,
        line: data.line,
        info: data.info,
        type: data.type
    }).save();
};

module.exports = log;

This simple function records the date when an error occurs, the file name, the line where this function has been invoked, the details of the error and the severity of the error occurred (e.g critical).

We can use the above function when we actually have to handle errors, for example with Promises:


'use strict';

const app = require('express')();
const users = require('./models/users');
const logs = require('./models/logs');
const log = require('./lib/log');

app.get('/users', async (req, res) => {
    try {
        const results = await users.find();
        res.send(results);
    } catch(err) {
        log({
            file: 'app.js',
            line: '10',
            info: err,
            type: 'critical'
        }, logs);
        res.sendStatus(500);
    }
});

Share: