9

I have a node mongo app. Now I want to show audit trail for some specific crud events which are happening in the application.

What would be the best approach for solving this problem ?

I have considered of creating a new collection and service which would be called in each method in node app for logging the operations.

Ved Agarwal
  • 565
  • 3
  • 6
  • 14

5 Answers5

5

It's better to use a different schema having all the logs that you want to store for particular actions.

// schema
var schema = new Schema({
    actionType: {type: String, require: true},
    userId: { type: Schema.Types.ObjectId, required: true },
    userType: { type: String, required: true },
    message: { type: String, required: true },
    createdAt: { type: Date, default: Date.now },

}, options);

Here you can log your activity logs with

What action have been taken. Which user. And the message that you want to store with that action etc.

Sachin
  • 2,912
  • 16
  • 25
4

You are talking about 'triggering'. But unfortunately "MongoDB does not support triggers".

For solving your issue simply create another collection and store the log information into that collection.

Reference :

Community
  • 1
  • 1
Libu Mathew
  • 2,976
  • 23
  • 30
1

you can add a middleware to you app which adds a bunyan child logger to each request with some unique id (probably uuid)

here is some sample code to attach a logger to each request with unique id, whenever you will print something using this logger, this uuid will also be printed automatically so you can trace each request using this id

var bunyan = require('bunyan');
var uuid = require('uuid');
var logger = bunyan.createLogger({name: 'some name'});
function loadlogger(req, res, next) {
    req.log = logger.child({request_id: uuid.v4()});
    next()
}
app.use(loadLogger);

and you can log when ever you want as follow

req.log.info({keys: values}, "message");
req.log.warn({keys: values}, "message");
req.log.error({keys: values}, "message");

You can refer to complete documentation bunyan logger

Community
  • 1
  • 1
suraj.tripathi
  • 417
  • 2
  • 15
1

If you are using mongoose module then there is method for logging all query.It'll log all queries on console.

mongoose.set('debug', true);

If you want to log in a file then use callback for this method

mongoose.set('debug', function (coll, method, query, doc [, options]) {
 //do your thing
});
Vaibhav Patil
  • 2,603
  • 4
  • 14
  • 22
1

For newer versions of mongodb (>=3.6) you can use mongodbs change stream. https://docs.mongodb.com/manual/changeStreams/

Based on that, you can track your changes you want and may save them separately in a file or a collection.

Here is a quick example:

const collection = db.collection('users');
const changeStream = collection.watch();
changeStream.on('change', next => {
  // do your stuff
});
Marco
  • 1,579
  • 1
  • 19
  • 34