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]
0

2 Answers 2

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"
  }
}
3

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

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

    optionsBuilder.UseLoggerFactory(_loggerFactory);
}
4
  • 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, 2017 at 2:54
  • 7
    Just for other who came here with the same problem read out this article. As this answer is not very helpful.
    – JB's
    May 4, 2017 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 8, 2018 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. Feb 28, 2020 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.