NestJS+TypeORM+MySQL环境下如何配置New Relic监控数据库操作
解决NestJS+TypeORM+MySQL环境下New Relic数据库监控问题
1. 确认New Relic依赖版本与扩展包
- 必须使用v8.0.0及以上版本的New Relic Node.js Agent,该版本开始原生支持TypeORM的监控 instrumentation。
- 安装NestJS和TypeORM对应的New Relic扩展包:
npm install @newrelic/nestjs @newrelic/typeorm --save
2. 配置New Relic Agent加载TypeORM监控
在项目根目录的newrelic.js配置文件中,添加TypeORM的instrumentation启用配置:
'use strict' exports.config = { app_name: ['你的应用名称'], license_key: '你的New Relic授权密钥', instrumentation: { '@newrelic/typeorm': { enabled: true }, '@newrelic/nestjs': { enabled: true } }, logging: { level: 'info' }, // 其他原有配置项... }
3. 规范TypeORM初始化方式
- 必须通过NestJS官方的
TypeOrmModule.forRoot()或forRootAsync()初始化数据库连接,禁止直接使用TypeORM原生的createConnection方法,否则New Relic无法拦截数据库操作。 - 示例NestJS模块配置:
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { AppController } from './app.controller'; import { AppService } from './app.service'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: 'your-db-password', database: 'your-db-name', entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: true, }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
4. 验证监控加载状态
- 通过New Relic Agent启动应用,命令如下:
node -r newrelic dist/main.js - 查看应用启动日志,确认存在
TypeORM instrumentation initialized类的输出,证明监控已成功加载。
5. 自定义查询的手动追踪(若有需要)
如果项目中使用了TypeORM的queryRunner.query()等自定义查询方法,需要手动添加New Relic追踪:
import newrelic from 'newrelic'; async function customUserQuery() { const segment = newrelic.startSegment('custom-mysql-user-query', true, () => {}); try { const result = await this.queryRunner.query('SELECT * FROM users WHERE id = ?', [1]); return result; } finally { segment.end(); } }
内容的提问来源于stack exchange,提问作者tagplus5
相关产品推荐
相关产品推荐

