You need to enable JavaScript to run this app. 如何在Elastic APM中统计.Net Core API端点执行的SQL查询总数
优惠活动
大模型
产品
解决方案
定价
更多

如何在Elastic APM中统计.Net Core API端点执行的SQL查询总数

基于.NET Core 2.2 + Elastic APM 实现EF SQL执行数事务级统计

核心逻辑说明

当前app.UseAllElasticApm(Configuration)已完成APM基础埋点,Elastic APM原生只会把EF Core执行的SQL捕获为事务下的子Span,不会自动在事务维度汇总执行次数,需要通过EF Core命令拦截器 + APM自定义标签的组合实现目标效果。

实现步骤

  • 匹配依赖版本
    由于项目使用.NET Core 2.2.3,需锁定兼容的依赖版本避免运行时异常:
  • Elastic.Apm.NetCoreAll 选用兼容2.2的最后一个稳定版本(1.12.1),更高版本会要求.NET Core 3.0+运行时
  • 确认项目引用的EF Core组件为2.2.x版本,和目标框架版本对齐
  • 编写EF Core命令计数拦截器
    利用EF Core 2.2提供的IDbCommandInterceptor接口,在每次SQL命令执行时累加计数,同时关联当前APM事务的标签:
public class SqlQueryCountInterceptor : IDbCommandInterceptor
{
    private readonly ICurrentApmTransaction _currentTransaction;

    public SqlQueryCountInterceptor(ICurrentApmTransaction currentTransaction)
    {
        _currentTransaction = currentTransaction;
    }

    // 拦截查询执行事件
    public void ReaderExecuted(DbCommand command, DbCommandExecutedEventData eventData) => IncrementSqlCount();
    // 拦截非查询(增删改)执行事件
    public void NonQueryExecuted(DbCommand command, DbCommandExecutedEventData eventData) => IncrementSqlCount();
    // 拦截标量查询执行事件
    public void ScalarExecuted(DbCommand command, DbCommandExecutedEventData eventData) => IncrementSqlCount();

    // 补全接口要求的空实现方法,无业务逻辑
    public void CommandInitialized(CommandEndEventData eventData) { }
    public void ReaderExecuting(DbCommand command, DbCommandExecutingEventData eventData) { }
    public void NonQueryExecuting(DbCommand command, DbCommandExecutingEventData eventData) { }
    public void ScalarExecuting(DbCommand command, DbCommandExecutingEventData eventData) { }

    private void IncrementSqlCount()
    {
        var currentTransaction = _currentTransaction.Value;
        // 无关联APM事务的场景直接跳过计数
        if (currentTransaction == null) return;

        // 读取当前事务已存的计数值
        var currentCount = 0;
        currentTransaction.Tags?.TryGetValue("EntityFramework.ExecutedSqlQueriesCount", out var originalValue);
        int.TryParse(originalValue?.ToString(), out currentCount);

        // 更新标签值
        currentTransaction.Tags["EntityFramework.ExecutedSqlQueriesCount"] = (currentCount + 1).ToString();
    }
}
  • 注册组件到依赖注入容器
    在Startup的ConfigureServices方法中,拦截器需注册为Scoped生命周期,和Web请求、APM事务的作用域完全对齐,避免跨请求计数串扰,同时把拦截器挂载到EF Core的管线中:
// 注册拦截器
services.AddScoped<SqlQueryCountInterceptor>();

// 修改原有DbContext注册逻辑,挂载拦截器
services.AddDbContext<AppDbContext>((serviceProvider, options) =>
{
    // 保留原有数据库连接配置
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    // 挂载拦截器
    options.AddInterceptors(serviceProvider.GetRequiredService<SqlQueryCountInterceptor>());
});

效果验证

启动应用后触发任意API请求,打开Kibana对应APM服务的事务详情页,在元数据标签区域即可看到EntityFramework.ExecutedSqlQueriesCount字段,数值对应当前事务生命周期内EF Core执行的所有SQL命令总量。

注意事项

  • 计数范围严格匹配APM事务边界:后台任务、HostedService等无Web事务关联的EF执行不会被计入该标签,完全匹配“每个事务下的SQL数量”的统计目标
  • APM事务的标签支持动态修改,数据上报时会自动携带最终的标签值,无需手动触发提交流程
  • 不要随意升级Elastic APM的依赖包版本,2.2框架下使用高版本APM SDK会出现类型加载异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.26 14:06:10