问题描述
我想用 nestJs 为 typeorm 实现自定义记录器.我的目标是在 MySQL 中存储查询.
I want to implement Custom Logger for typeorm with nestJs. my goal is to store queries in MySQL.
首先我创建一个实体:
@Entity('log')
export class LogModel extends BaseEntity {
@PrimaryGeneratedColumn()
id: number
@Column({ nullable: true, type: "text" })
query: string
}
然后创建一个自定义记录器类,如下所示:
then create a custom logger class like the following :
import { Logger, QueryRunner } from 'typeorm'
export class CustomLogger implements Logger {
logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner) {
this.saveLog(queryRunner)
}
private async saveLog(queryRunner: QueryRunner) {
if (queryRunner) {
const log = new LogModel()
log.query='my query ....'
const repository = queryRunner.connection.getRepository<LogModel>(LogModel)
await repository.save(log) // calls more than 1000
}
}
logQueryError(error: string | Error, query: string, parameters?: any[], queryRunner?: QueryRunner) {}
logQuerySlow(time: number, query: string, parameters?: any[], queryRunner?: QueryRunner) {}
logSchemaBuild(message: string, queryRunner?: QueryRunner) { }
logMigration(message: string, queryRunner?: QueryRunner) { }
log(level: 'log' | 'info' | 'warn', message: any, queryRunner?: QueryRunner) { }
}
在最后一步中,我在 typeorm 配置中使用了上面的 CustomLogger 类:
and in the last step I use the CustomLogger class above in typeorm config:
const typeOrmConfig: TypeOrmModuleOptions = {
type: 'mysql',
host: 'localhost',
port: 3306,
logging: ['warn', 'error'],
charset: "utf8mb4_unicode_ci",
cli: {
migrationsDir: 'src/migrations'
},
....
maxQueryExecutionTime: 1000,
logger: new CustomLogger()
}
任何帮助将不胜感激
推荐答案
我相信您已经创建了一个递归函数.您运行一个查询,该查询调用记录器,该查询运行一个调用该记录器的查询,该查询运行一个调用该记录器的查询(等等).您可能需要直接使用数据库驱动程序,以免干扰 TypeORM 查询周期,并将日志查询与常规查询分开.
I believe you've created a recursive function. You run a query, that calls the logger, that runs a query that calls the logger that runs a query that calls the logger (etc.). You'd need to probably use a database driver directly to not interfere with the TypeORM query cycle and to keep the logging queries separate from the regular queries.
这篇关于typeorm 在自定义记录器中保存调用超过 1000 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!