13

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]
codersl
  • 2,222
  • 4
  • 30
  • 33

2 Answers2

6

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"
  }
}
Pingolin
  • 3,161
  • 6
  • 25
  • 40
Sharon Zhou
  • 61
  • 1
  • 4
3

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

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

    optionsBuilder.UseLoggerFactory(_loggerFactory);
}
codersl
  • 2,222
  • 4
  • 30
  • 33
  • 2
    Just to note to others reading the above code: the `_loggerFactory` parameter is set using constructor dependency injection in your `FooContext` class. – Matt Jan 29 '17 at 02:54
  • 7
    Just for other who came here with the same problem read out [this article](https://learn.microsoft.com/en-us/ef/core/miscellaneous/logging). As this answer is not very helpful. – JB's May 04 '17 at 11:24
  • If you use asp.net mvc core, no need to do anything, just make sure that the logging verbosity is "info". – meze May 08 '18 at 19:11
  • @meze it does not matter whether you use .NET Core or not, if you're registering your `DbContext` with `services.AddDbContext(...)`. This method assures that applications standard logging factory is already registered, or it throws an exception if it is not able to find one. – Buğra Ekuklu Feb 28 '20 at 18:31