如何在ASP .Net Core中记录Pomelo发送给MySQL的SQL查询语句
ASP .Net Core 3.1 + Pomelo EF Core 查看SQL日志问题解决
环境版本
- ASP .Net Core 3.1
- Pomelo.EntityFrameworkCore.MySql 3.1.0
问题
希望查看项目中Pomelo发送给MySQL的已执行SQL查询语句,预期日志显示在Visual Studio 2022的输出面板中,但目前无法看到相关日志。
已执行操作
- 在
ConfigureServices方法的services.AddDbContextPool中添加了options.EnableSensitiveDataLogging(); - 更新
appsettings.Development.json配置如下:
"Logging": { "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information", "Microsoft.EntityFrameworkCore": "Information", "Microsoft.EntityFrameworkCore.Database.Command": "Debug" } }
参考资料
- 《如何使用.NET Core内置日志查看Entity Framework Core生成的SQL》
- 《ASP.NET Core 2.2 Entity Framework 日志记录》
解决方案
补充控制台日志配置
Visual Studio输出面板依赖控制台日志提供器,需在appsettings.Development.json中明确配置控制台输出的日志级别:"Logging": { "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information", "Microsoft.EntityFrameworkCore": "Information", "Microsoft.EntityFrameworkCore.Database.Command": "Debug" }, "Console": { "IncludeScopes": true, "LogLevel": { "Microsoft.EntityFrameworkCore.Database.Command": "Debug" } } }完善DbContext配置
在AddDbContextPool中同时启用详细错误日志(可选但有助于排查),确保配置完整:services.AddDbContextPool<YourDbContext>(options => options.UseMySql("你的数据库连接字符串", new MySqlServerVersion(new Version(8, 0, 21))) // 根据你的MySQL版本调整 .EnableSensitiveDataLogging() .EnableDetailedErrors());检查Visual Studio输出面板设置
- 打开输出面板:点击顶部菜单「视图」→「输出」
- 在面板顶部的「显示输出来自」下拉框中选择「ASP.NET Core Web Server」
- 确保未过滤Debug级别的日志
确认运行环境
检查项目的launchSettings.json,确保ASPNETCORE_ENVIRONMENT设置为Development,只有开发环境下调试日志才会正常输出。
内容的提问来源于stack exchange,提问作者Herbert
相关产品推荐
相关产品推荐

