Papooch / nestjs-cls

A continuation-local storage (async context) module compatible with NestJS's dependency injection.
https://papooch.github.io/nestjs-cls/
MIT License
434 stars 28 forks source link

Why can't I get context data in Typeorm's logQuerySlow when logQuery does #27

Closed ahuijiLearning closed 2 years ago

ahuijiLearning commented 2 years ago
// app.module.ts
@Module({
  imports: [
    ClsModule.register({
      global: true,
      interceptor: {
        generateId: true,
        mount: true,
        setup: (cls: ClsService, context: ExecutionContext) => {
          cls.set('startTime', +new Date());
        },
      },
    }),
TypeOrmModule.forRoot({
      ...config.mysql,
     maxQueryExecutionTime: 0.1,
      logger: new OrmLogger(),
    }),
],
})
export class AppModule { }

// controller.ts
@ApiOperation({ summary: 'log 测试' })
@Get('log')
async log(@Query('id', new ParseIntPipe()) id: number): Promise<any> {
   return await this.userRepository.find({
      where: {
        id,
      }
    });
}

// OrmLogger.ts
import { ClsServiceManager } from 'nestjs-cls';
import { Log } from 'src/common/logger/';
import { Logger, QueryRunner } from "typeorm";

export class OrmLogger implements Logger {
  logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner) {
        const cls = ClsServiceManager.getClsService();
        console.log(`${cls.get('startTime')}  Executed: ${query}`);
    }
  logQuerySlow(time: number, query: string, parameters?: any[], queryRunner?: QueryRunner) {
        const cls = ClsServiceManager.getClsService();
        console.log(`${cls.get('startTime')} Executed: ${query} time: ${time}ms`);
    }
}

// console
1649417986277  Executed: SELECT `User`.`id` AS `User_id`, `User`.`truename` AS `User_truename`, `User`.`studentid` AS `User_studentid` FROM `user` `User` WHERE `User`.`id` IN (?)
undefined Executed: SELECT `User`.`id` AS `User_id`, `User`.`truename` AS `User_truename`, `User`.`studentid` AS `User_studentid` FROM `user` `User` WHERE `User`.`id` IN (?) time: 19ms

What is the cause of this, and what solutions are available

Papooch commented 2 years ago

Hi, I have no experience with TypeORM's Logger. This is the first time I've seen the logQuerySlow method and I can't find much documentation about it. I assume that they use some kind of asynchronous event system that logs the slow query outside the context of the request.

But before going any further, I think I found your question on StackOverflow regarding the same thing, but using plain AsyncLocalStorage.

If it doesn't work with plain AsyncLocalStorage, then there's sadly nothing I can change in my package to make it work and I recommend opening an issue in the TypeORM's github repository.

The only "solution" as of right now would be to use a different ORM.