Search code examples
node.jsrestifybunyan

Restify - Best practice for accessing logger from a module


I have looked for the answer to this for a while and just have not come up with a solution. I understand that I have access to the builtin logger from req.log.xxxxx(...), but what about a module that I have required into my controller? For example:

in my controller file, someController.js

var myModule = require('myModule');

SomeController.listUsers = function listUsers(req, res, next){
    req.log.info('Some log message'); // <---- this works just fine
    //... 
}

In myModule.js:

module.exports = {
    getUsers: function () {
        // ...
        // I would like to be able to log from here, but don't have access to the req object.
    }
}

I don't really like the idea of passing the log object to the module's method, as that seems sloppy to me. If that's the only solution, then I'll live with it.


Solution

  • Restify uses bunyan to provide logging.

    Looking through the documentation, the logger that's used for req.log is the one that's created at server startup (or at least a child of that logger). Since you can also create your own logger instance, I think that this should work:

    // logger.js
    var bunyan = require('bunyan');
    module.exports = bunyan.createLogger(...);
    
    // app.js
    var server = restify.createServer({
      log : require('./logger')
    });
    
    // someController.js
    var logger = require('./logger');
    ...
    

    This shares the same logger between the Restify server and other parts of your application. If you don't necessarily require that the logger is the same, you can also just create a new Bunyan instance in someController.js.