Scott Baker
Scott Baker

Reputation: 10453

EF Core 2.2 LoggerFactory not Logging DB commands to Console

I'm trying to implement logging database commands from my DbContext to a console window so I can examine the T-SQL queries before they're sent to the database.

I defined an ILoggerFactory in my 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)
    });

and added it to the Startup services configuration:

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

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

... from watching @JulieLerman EF Core videos I was expecting a Console window to pop up every time before my DbContext issued a T-SQL statement to the database - but for me, nothing happens. I hit my breakpoints in my _context.Things.ToList() or _context.Things.Find(id) but no logging window appears, it just shows the error from the database in the browser window.

I tried changing the configuration of the ConsoleLoggerProvider to catch more log events:

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

... but still no console window, at all. What am I forgetting?

Upvotes: 0

Views: 1612

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239380

  1. Queries are logged to the console by default. You don't need to do anything.

  2. The console window isn't going to just pop up. You have to be running in a console window, and then logs will display there, i.e. dotnet run MyProject.csproj at a command line. If you're running in Visual Studio, you won't get a console window, but the console output can be viewed in the Output pane. In the dropdown on that pane, choose "ASP.NET Core Web Server".

  3. In all other scenarios (IIS, etc.), logging to console isn't going to do anything for you, as there's no way to see it. You can redirect the output to another logging provider using config. See: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2#log-filtering

Upvotes: 4

Related Questions