如何将bunyan日志loggingfunction绑定到ES6中的类function?

今天有一点烦恼,仍然有一个错误。 文档在这里。 最近的我是这样的:

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; } 

在class上的其他地方,我发送一个bunyanlogging器的function:

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

logging器只是使用控制台输出。 如果我传递console.logconsole.error但是如果我传递Bunyanlogging器,则失败:

 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 } 

有一个关于这个github问题,但它并没有真正清楚如何解决它。 如何将一个bunyanlogging器函数(如logger.error给另一个对象? 这可能吗?

如果它抱怨this是因为当你发送logger.debug函数时this上下文丢失了。

使用ES6胖箭头function来解决这个问题。

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

如果期望绑定到上下文,则不应将未绑定的对象方法作为callback进行传递。 可以将console方法作为callback传递,因为它们在大多数现代实现中都被绑定到console ,但是这不应该被跨平台代码所暗示。

console方法已经绑定到Node.js的console ,并可以安全地传递callback没有额外的措施。

对于其他方法,应该是:

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