Skip to content

Instantly share code, notes, and snippets.

@bromanko
Created October 25, 2012 14:45
Show Gist options
  • Save bromanko/3952984 to your computer and use it in GitHub Desktop.
Save bromanko/3952984 to your computer and use it in GitHub Desktop.
Express Middleware for Bunyan logging
var bunyan = require('bunyan');
module.exports.logger = function logger(log) {
if (typeof (log) !== 'object')
throw new TypeError('log (Object) required');
this.log = log;
var self = this;
return function logger(req, res, next) {
req.log = log;
self.log.info({req: bunyan.stdSerializers.req(req)}, 'start');
next();
};
};
module.exports.errorLogger = function(log) {
if (typeof (log) !== 'object')
throw new TypeError('log (Object) required');
this.log = log;
var self = this;
return function logger(err, req, res, next) {
if (err)
self.log.trace({err: err}, 'error');
next();
};
};
@qubyte
Copy link

qubyte commented Jul 15, 2013

The use of this looks dangerous. These are not constructors, so this refers to the scope of the module, allowing strange behaviour with collisions. There doesn't appear to be any need to use this, as the scope should take care of itself:

var bunyan = require('bunyan');

module.exports.logger = function logger(log) {
  if (typeof log !== 'object') {
    throw new TypeError('log (Object) required');
  }

  return function logger(req, res, next) {
    req.log = log;
    log.info({ req: bunyan.stdSerializers.req(req) }, 'start');
    next();
  };
};

module.exports.errorLogger = function(log) {
  if (typeof log !== 'object') {
    throw new TypeError('log (Object) required');
  }

  return function logger(err, req, res, next) {
    if (err) {
      log.trace({ err: err }, 'error');
    }

    next();
  };
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment