Enable raw SQL logging in Entity Framework Core

c# entity-framework

Question

How do I enable the logging of DbCommand raw SQL queries?

I have added the following code to my Startup.cs file, but do not see any log entries from the Entity Framework Core.

void ConfigureServices(IServiceCollection services)
{
    services.AddLogging();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug(LogLevel.Debug);
}

I'm expecting to see something like this:

Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandBuilder...
SELECT [t].[Id], [t].[DateCreated], [t].[Name], [t].[UserName]
FROM [Trips] AS [t]
1
10
9/2/2016 1:09:42 AM

Accepted Answer

Figured it out - need to configure DbContext to use logger factory.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    base.OnConfiguring(optionsBuilder);

    optionsBuilder.UseLoggerFactory(_loggerFactory);
}
4
9/2/2016 3:33:57 AM

Popular Answer

From MVC Core 2, logging SQL is the default behaviour. Just make sure logging level in appSettings json file is correct.

"Logging": {
  "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
  }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow