Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

contextFormat 对 appLogger 不生效 #123

Open
geekberryonekey opened this issue Jun 17, 2024 · 4 comments
Open

contextFormat 对 appLogger 不生效 #123

geekberryonekey opened this issue Jun 17, 2024 · 4 comments

Comments

@geekberryonekey
Copy link

版本: @midwayjs/logger: 3.4.0

  midwayLogger: {
    default: {
      transports: {
        console: {
          level: 'debug',
        },
        file: {
          level: 'debug',
          dir: `logs/${injectedEnv.nodeEnv}/${injectedEnv.project}`,
        },
        error: false,
      },
    },
    clients: {
      appLogger: {
        fileLogName: 'app.log',
        format: formatLogger,
        contextFormat: formatLogger,
      },
    },
  },
@Middleware()
export class TraceIdMiddleware implements IMiddleware<Context, NextFunction> {
  @Inject()
  logger: ILogger;

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      console.log(this.logger === ctx.logger); // false
      console.log(ctx.getLogger() === ctx.logger); // true

      ctx.logger.error('ctx.logger'); // 没有到 formatLogger
      this.logger.error('this.logger'); // 走到了 formatLogger

      return await next();
    };
  }
}
@geekberryonekey
Copy link
Author

geekberryonekey commented Jun 21, 2024

以下是各种注入方式和行为表现:

@Controller('/v1/health')
export class HealthController {
  @Logger('customLogger') // 能输出, 能被 format 处理, 不等于 ctx.logger
  // @Logger('appLogger') // 能输出, 能被 format 处理, 不等于 ctx.logger
  // @Logger() // this.myLogger === undefined
  // @Inject() // this.myLogger === undefined
  myLogger: ILogger; // 名字不叫 logger

  // @Logger('customLogger') // 能输出, 能被 format 处理 (自定义 logger), 不等于 ctx.logger
  // @Logger('appLogger') // 能输出, 能被 format 处理, 不等于 ctx.logger
  // @Logger() // 能输出, 能被 format 处理, 不等于 ctx.logger
  @Inject() // 能输出, 不能被 format 处理, 不能被 contextFormat 拦截, 等于 ctx.logger
  logger: ILogger;

  @Inject()
  ctx: Context;

  @Get('/')
  async health() {
    this.myLogger.info('myLogger');
    this.logger.info('logger');
    this.ctx.logger.info('ctx.logger');

    return true;
  }
}

@geekberryonekey
Copy link
Author

format 和 contextFormat 是 clients 的两个参数是吧, 请看我上文的测试结果, 均不能被 contextFormat 拦截
(而能被 format 拦截的, ctx 都是 null)

@czy88840616
Copy link
Member

czy88840616 commented Jun 21, 2024

文档里的链接底下有特殊场景,原因是 web framework 类型覆盖了 appLogger 的 context format,这里的确不好理解,下个大版本是计划重构掉的。

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants