首页 > 解决方案 > EF Core 2.2 LoggerFactory 未将 DB 命令记录到控制台

问题描述

我正在尝试将数据库命令从我DbContext的日志记录到控制台窗口,以便在将 T-SQL 查询发送到数据库之前对其进行检查。

ILoggerFactory在我的DbContext

public class PocContext : DbContext
{
    public static readonly ILoggerFactory MyLoggerFactory = new LoggerFactory(new[]
    {
        new ConsoleLoggerProvider((cat, lvl) =>
            cat == DbLoggerCategory.Database.Command.Name &&
            lvl == LogLevel.Information, true)
    });

并将其添加到Startup服务配置中:

public void ConfigureServices(IServiceCollection services)
{
    // ... other config stuff

    services.AddDbContext<PocContext>(options =>
        options
            .UseLoggerFactory(PocContext.MyLoggerFactory)
            .EnableSensitiveDataLogging()
            .UseOracle(_configuration.GetConnectionString("Foo"))
    );

DbContext...通过观看@JulieLerman EF Core 视频,我希望每次在向数据库发出 T-SQL 语句之前都会弹出一个控制台窗口- 但对我来说,什么都没有发生。我在我的_context.Things.ToList()_context.Things.Find(id)但没有出现日志记录窗口中打断点,它只是在浏览器窗口中显示来自数据库的错误。

我尝试更改 ConsoleLoggerProvider 的配置以捕获更多日志事件:

public class PocContext : DbContext
{
    public static readonly ILoggerFactory MyLoggerFactory = new LoggerFactory(new[]
    {
        new ConsoleLoggerProvider((cat, lvl) => true, true)
    });

...但仍然没有控制台窗口。我忘记了什么?

标签: c#loggingdbcontextasp.net-core-2.1ef-core-2.2

解决方案


  1. 查询默认记录到控制台。你不需要做任何事情。

  2. 控制台窗口不会只是弹出。您必须控制台窗口中运行,然后日志将显示在那里,即dotnet run MyProject.csproj在命令行中。如果您在 Visual Studio 中运行,您将不会获得控制台窗口,但可以在“输出”窗格中查看控制台输出。在该窗格的下拉列表中,选择“ASP.NET Core Web 服务器”。

  3. 在所有其他情况下(IIS 等),登录到控制台不会为您做任何事情,因为您无法看到它。您可以使用 config 将输出重定向到另一个日志记录提供程序。请参阅:https ://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2#log-filtering


推荐阅读