How do I bind a bunyan logging function to a class function in ES6?

1k Views Asked by At

Fussing with this one a bit today, still getting an error. Docs here. Closest I have is this:

constructor(region, sslEnabled = true, 
     logger = () => {}, errorLogger = () => {}) {
if (region === undefined || !region)
  throw new Error("Initialization error: region is required");

  this.log = () => {};           // these two lines might be unnecessary
  this.logError = () => {};      //
  this.log = logger.bind(this);
  this.logError = errorLogger.bind(this);
  this.region = region;
  this.sslEnabled = sslEnabled;
}

Elsewhere in the class I send a bunyan logger's functions in:

const tools = new Tools(
  config.region,
  config.ssl,
  logger.debug,
  logger.error
);

The logger is just using console output. This works if I pass console.log and console.error but fails if I pass Bunyan loggers:

bunyan usage error: /usr/src/app/src/healthcheck.js:47: 
 attempt to log with an unbound log method: `this` is: TTools {
  log: [Function: bound ],
  logError: [Function: bound ],
  region: 'us-west-2',
  sslEnabled: false }

There is a github issue about this but it didn't really make it clear how to fix it. How do I pass a bunyan logger function like logger.error to another object? Is this possible?

2

There are 2 best solutions below

0
On BEST ANSWER

If its complaining about this then that's because the this context is lost when you send logger.debug function.

Use ES6 fat arrow function to get around this problem.

const tools = new Tools(
  config.region,
  config.ssl,
  x => logger.debug(x),
  x => logger.error(x)
);
0
On

Unbound object methods should never be passed as callbacks if they are expected to be bound to their context. It is possible to pass console methods as callbacks because they are bound to console in most modern implementations, but this should never be implied in cross-platform code.

console methods are already bound to console in Node.js and can be safely passed as callbacks without additional measures.

For other methods, it should be:

const tools = new Tools(
  config.region,
  config.ssl,
  logger.debug.bind(logger),
  logger.error.bind(logger)
);