I am using express.js. I have a need to be able to log certain request data whenever someone tries to log a message. For this I would like to create a helper method like so
function log_message(level, message){
winston.log(level, req.path + "" + message);
}
I would then use the method like so.
exports.index = function(req, res){
log_message("info", "I'm here");
}
Note that I am not passing the req object to the log_message function. I want that to be transparently done so that the log_message API user does not need to be aware of the common data that is being logged.
Is there a way to achieve this with express.js/node.js. Is the request object available from a global variable of some sort?
use(function(req, res, next) { req. getUrl = function() { return req. protocol + "://" + req.
NodeJS has its own EventLoop which is an infinite loop that receives requests and processes them. EventLoop is the listener for the EventQueue. If NodeJS can process the request without I/O blocking then the event loop would itself process the request and sends the response back to the client by itself.
No, it is not blocking - hence why the callback is required to handle the asynchronous result. Naturally, if there is a required serialized relationship then the previous requests must complete in order to use the results ..
Similar to the domains answer, it's now a lot easier to do this using continuation-local-storage: https://datahero.com/blog/2014/05/22/node-js-preserving-data-across-async-callbacks/
At DataHero we save a transaction id, user id, and session id with all log messages. You don't need to pass the request object all the way down, so it helps keep your models / business layer clean, too.
create a midleware:
app.use(function(req, res, next) {
var tid = uuid.v4();
var cls = require('continuation-local-storage');
var namespace = cls.createNamespace('com.storage');
var pre_ip;
if(get_ip(req))
{ ip_info= get_ip(req).clientIp;
pre_ip=ip_info
}
namespace.bindEmitter(req);
namespace.bindEmitter(res);
namespace.run(function() {
console.log(logobj);
namespace.set('tid', tid);
namespace.set('ip',ip_info);
namespace.set('logobj',logobj);
next();
});
});
And use it :
var cls = require('continuation-local-storage');
var namespace = cls.getNamespace('com.storage');
namespace.get('ip');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With