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"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

    optionsBuilder.UseLoggerFactory(_loggerFactory);
}

4 Comments

Just to note to others reading the above code: the _loggerFactory parameter is set using constructor dependency injection in your FooContext class.
Just for other who came here with the same problem read out this article. As this answer is not very helpful.
If you use asp.net mvc core, no need to do anything, just make sure that the logging verbosity is "info".
@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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.