You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nest Express应用Sentry配置为何仅显示http.server span?

解决Nest集成Sentry仅显示'http.server' Span的问题

关键修复步骤

1. 补全Http集成的追踪配置

你的Sentry Http集成未开启追踪开关,默认不会捕获HTTP请求的Span,修改集成配置:

new Sentry.Integrations.Http({ tracing: true }), // 显式开启HTTP调用的Span追踪

2. 改用Nest官方Sentry模块配置

直接使用@sentry/node的原生配置在Nest环境下覆盖不全,换成Nest封装的Sentry模块:

import { SentryModule } from '@nestjs/sentry';

@Module({
  imports: [
    SentryModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        dsn: configService.get('SENTRY_DSN'),
        tracesSampleRate: +configService.get('SENTRY_SAMPLE_RATE'),
        sampleRate: +configService.get('SENTRY_SAMPLE_RATE'),
        environment: configService.get('NODE_ENV'),
        debug: true,
        attachStacktrace: true,
        integrations: [
          new Sentry.Integrations.Http({ tracing: true }),
          new Sentry.Integrations.Mysql(),
          new Sentry.Integrations.Modules(),
          new Sentry.Integrations.Express(),
        ],
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}

3. 严格控制中间件加载顺序

Sentry的中间件必须放在所有其他中间件、路由注册之前,保证请求全链路被追踪:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 先加载Sentry请求处理和追踪中间件
  app.use(Sentry.Handlers.requestHandler({
    ip: true,
    request: true,
    transaction: true,
    user: true,
  }));
  app.use(Sentry.Handlers.tracingHandler());

  // 再加载CORS、管道等其他中间件
  app.enableCors();
  app.useGlobalPipes(new ValidationPipe());

  // 最后加载错误处理中间件
  app.use(Sentry.Handlers.errorHandler());

  await app.listen(3000);
}
bootstrap();

4. 确保数据库集成生效

如果使用TypeORM而非原生mysql/mysql2包,Sentry的Mysql集成可能无法自动捕获,需要手动包裹数据库操作生成Span:

async findAllUsers() {
  const span = Sentry.startSpan({ name: 'UserService.findAll', op: 'db.query' });
  try {
    const users = await this.userRepository.find();
    span.setStatus('ok');
    return users;
  } catch (err) {
    span.setStatus('internal_error');
    throw err;
  } finally {
    span.end();
  }
}

5. 清理冗余依赖

移除@sentry-internal/tracing,@sentry/node已经包含完整的追踪功能,避免版本冲突。

内容的提问来源于stack exchange,提问作者Milad Ashoori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:53:32