配置EF Core日志后未输出SQL至控制台,求指导实现
解决EF Core查询SQL语句不显示的问题
问题根源
你使用的DebugLoggerProvider已过时,且它默认将日志输出到Visual Studio的调试输出窗口而非控制台;同时你的日志过滤规则仅开启了开关,未明确指定EF Core相关的日志类别与级别,导致SQL查询日志未被捕获输出。
修复方案
1. 更换日志包(推荐)
弃用Microsoft.Extensions.Logging.Debug,改用Microsoft.Extensions.Logging.Console,它直接将日志输出到控制台,更贴合你的需求。通过NuGet包管理器安装:
Install-Package Microsoft.Extensions.Logging.Console
2. 更新DbContext配置
修改MyDbnContext代码,使用控制台日志提供器,并明确开启EF Core的SQL命令日志级别:
public partial class MyDbnContext : DbContext { private static readonly ILoggerFactory _loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole() .AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Information); }); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseLoggerFactory(_loggerFactory); } }
3. 验证效果
执行查询后,控制台会输出类似如下的SQL日志内容:
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (3ms) [Parameters=[@__p_0='1'], CommandType='Text', CommandTimeout='30']
SELECT [m].[Id], [m].[Name]
FROM [MyTable] AS [m]
WHERE [m].[Id] = @__p_0
若坚持使用DebugLogger(不推荐)
如果一定要保留原DebugLoggerProvider,需做以下调整:
- 打开Visual Studio的输出窗口(而非控制台),选择“调试”输出类别
- 修改日志过滤规则,明确包含EF Core的命令日志:
public static readonly LoggerFactory LoggerFactory = new LoggerFactory(new[] { new DebugLoggerProvider((category, level) => category == "Microsoft.EntityFrameworkCore.Database.Command" && level >= LogLevel.Information) });
此时SQL日志会显示在VS的输出窗口中,而非控制台。
内容的提问来源于stack exchange,提问作者Mirza
相关产品推荐
相关产品推荐

