Application Insights无法显示Blazor应用数据库的SQL查询怎么办?
问题原因及解决方案
问题原因
出现这种差异的核心原因是两个数据库上下文的日志/跟踪配置不一致:
- Identity库的DbContext默认开启了敏感数据日志记录,且Application Insights能捕获到其SQL查询日志;
- 应用数据库的DbContext未配置相关日志,或Application Insights的SQL命令文本跟踪未启用,导致仅能捕获服务器和数据库名称,无法获取实际查询语句。
解决步骤
1. 开启应用数据库上下文的敏感数据日志记录
在应用数据库的DbContext类的OnConfiguring方法中,添加敏感数据日志配置:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // 仅在开发环境开启敏感数据日志,避免生产环境泄露敏感信息 var isDevEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == Environments.Development; optionsBuilder.EnableSensitiveDataLogging(isDevEnv); // 同时确保日志级别包含EF数据库命令日志 optionsBuilder.LogTo(_ => {}, LogLevel.Information); }
2. 确保Application Insights启用SQL命令文本跟踪
在appsettings.json中配置Application Insights,开启SQL命令文本捕获:
"ApplicationInsights": { "InstrumentationKey": "你的InstrumentationKey", "DependencyTracking": { "EnableSqlCommandTextInstrumentation": true } }
3. 配置EF命令日志级别
在appsettings.json的日志配置中,确保EF数据库命令的日志级别足够:
"Logging": { "LogLevel": { "Microsoft.EntityFrameworkCore.Database.Command": "Information" } }
4. 验证DbContext注册方式
确保应用数据库的DbContext正确注册到依赖注入容器,保证Application Insights能拦截其操作:
// Program.cs中注册DbContext builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("ApplicationDbConnection")));
完成以上配置后,重启应用并执行数据库操作,再次查看Application Insights的依赖详情,即可看到应用数据库的实际SQL查询语句。
内容的提问来源于stack exchange,提问作者David Thielen
相关产品推荐
相关产品推荐

