javascript - 如何将 bunyan 日志记录函数绑定(bind)到 ES6 中的类函数?

标签 javascript node.js logging ecmascript-6 bunyan

今天有点小题大做了,还是报错。 Docs here.我最接近的是:

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

在类的其他地方,我发送了一个 bunyan 记录器的函数:

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

记录器只是使用控制台输出。如果我通过 console.logconsole.error 这会起作用,但如果我通过 Bunyan 记录器则失败:

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 上有一个关于此的问题,但并没有真正说明如何修复它。如何将像 logger.error 这样的 bunyan 记录器函数传递给另一个对象?这可能吗?

最佳答案

如果它提示 this 那是因为当您发送 logger.debug 函数时 this 上下文丢失了。

使用 ES6 粗箭头函数解决这个问题。

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

关于javascript - 如何将 bunyan 日志记录函数绑定(bind)到 ES6 中的类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47602794/

相关文章:

javascript - 在数据表上显示列的总和(总计)并导出到 Excel

javascript - 如何监听由网络摄像头错误 : NotAllowedError 触发的全局事件

javascript - 将 javascript 数组从多维转换为关联

node.js - NodeJS module.exports 没有按预期工作

node.js - 连接到 LDAP 并绑定(bind)到更多 "general"DN 来搜索用户需要什么?

Tomcat catalina.out 一直增长直到服务器崩溃

javascript - javascript 中字符串的字符替换掩码

java - HashMap 中的记录器

java - 更改 logback 日志级别

node.js - 运行 npm run dev 时 env-cmd 路径错误