gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:56:31 25 4
gpt4 key购买 nike

今天有点小题大做了,还是报错。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com