传递给嵌套工具函数时Pino Logger无法正常工作的问题排查
Pino Logger传递到嵌套工具函数后无日志输出问题排查
我清楚依赖注入是这类场景的最佳方案,但当前遇到一个实际问题:把Pino logger传给工具函数,该函数又需要把logger传给另一个工具函数。logger在第一个工具函数里能正常输出日志,但第二个函数里完全没反应。
父类代码
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}}`; }
当前日志输出
> INFO (xx1): This is the doSomething function > INFO (xx2): this is the magicUtil function
预期应该出现的日志> INFO (xx2): this is the behindTheScenes function并未输出,以下是可能的原因及解决办法:
1. 函数访问权限问题
检查behindTheScenes函数的作用域:如果它和magicUtil不在同一个文件,且未被导出,会导致magicUtil无法正确调用它。确保两个函数在同一作用域内,或者behindTheScenes被正确导出并导入。
2. Pino日志级别配置错误
如果你的logger实例的日志级别高于info(比如warn、error),info级别的日志会被自动过滤。可以通过以下代码确认当前级别:
console.log(logger.level); // 输出当前日志级别,需为"info"才会显示目标日志
若级别不符,初始化logger时指定正确级别:
import pino from 'pino'; const logger = pino({ level: 'info' });
3. Pino子logger上下文丢失
如果传递的是通过logger.child()创建的子logger,可能存在上下文配置异常。尝试直接传递根logger测试,或者检查子logger的配置是否继承了正确的日志级别和输出设置。
4. 代码执行分支被跳过
确认behindTheScenes是否真的被执行:在函数开头添加普通console.log测试:
const behindTheScenes = (logger: pino.BaseLogger, value: string): string => { console.log('已进入behindTheScenes函数'); // 验证执行路径 logger.info('this is the behindTheScenes function'); return `something spectacular happened to value {${value}}`; }
如果该console.log也未输出,说明magicUtil中存在条件分支跳过了behindTheScenes的调用,检查调用逻辑是否存在遗漏。
内容的提问来源于stack exchange,提问作者physicsboy
相关产品推荐
相关产品推荐

