首先,我知道依赖注入是最好的选择,但这就是我目前所处的情况。
我有一个 Pino 记录器,我将其传递给一个实用函数,而该函数又想将其再次传递给另一个实用函数。
我似乎可以让记录器在第一个实用程序中工作,但不能在第二个实用程序中工作...出了什么问题以及如何让它在这种情况下工作?
家长班
import {magicUtil} from './utils';
class MyClass {
private logger;
constructor(logger: pino.BaseLogger) {
this.logger = logger;
}
doSomething() {
this.logger.info('This is the doSomething function');
return magicUtil(this.logger, 'some value');
}
}
实用工具
const magicUtil = (logger: pino.BaseLogger, value: string): string => {
logger.info('this is the magicUtil function');
return behindTheScenes(logger, value);
}
const behindTheScenes = (logger: pino.BaseLogger, value: string): string => {
logger.info('this is the behindTheScenes function;);
return `something spectacular happened to value {${value}}`;
}
在这种情况下,当我点击
doSomething()
时,我在日志中看到:
> INFO (xx1): This is the doSomething function
> INFO (xx2): this is the magicUtil function
我没有得到
> INFO (xx2): this is the behindTheScenes function
的最终预期日志。
我在这里缺少什么?
更正代码中的拼写错误并添加 MRE 所需的内容,我无法使用
[email protected]
重现此内容。
{
"type": "module",
"dependencies": {
"pino": "^9.4.0"
}
}
import pino from "pino";
class MyClass {
constructor(logger) {
this.logger = logger;
}
doSomething() {
this.logger.info("This is the doSomething function");
return magicUtil(this.logger, "some value");
}
}
const magicUtil = (logger, value) => {
logger.info("this is the magicUtil function");
return behindTheScenes(logger, value);
};
const behindTheScenes = (logger, value) => {
logger.info("this is the behindTheScenes function");
return `something spectacular happened to value {${value}}`;
};
const logger = pino();
const myClass = new MyClass(logger);
myClass.doSomething();
$ node a.js
{"level":30,"time":1728547536704,"pid":67619,"hostname":"Nova.local","msg":"This is the doSomething function"}
{"level":30,"time":1728547536704,"pid":67619,"hostname":"Nova.local","msg":"this is the magicUtil function"}
{"level":30,"time":1728547536704,"pid":67619,"hostname":"Nova.local","msg":"this is the behindTheScenes function"}