Log Queries executed by Entity Framework DbContext

C#LinqEntity Frameworkasp.net Mvc-5Entity Framework-6

C# Problem Overview


I'm using EF 6.0 with LINQ in MVC 5 project. I want to log all the SQL queries executed by the Entity Framework DbContext for debugging/performance-measurement purpose.

In Java/Hibernate, equivalent behavior can be achieved by setting the property hibernate.show_sql=true. Is it possible to have a similar behavior in Entity Framework?

C# Solutions


Solution 1 - C#

Logging and Intercepting Database Operations article at MSDN is what your are looking for.

The DbContext.Database.Log property can be set to a delegate for any method that takes a string. Most commonly it is used with any TextWriter by setting it to the “Write” method of that TextWriter. All SQL generated by the current context will be logged to that writer. For example, the following code will log SQL to the console:

using (var context = new BlogContext())
{
    context.Database.Log = Console.Write;

    // Your code here...
}

Solution 2 - C#

You can use this line to log the SQL queries to the Visual Studio "Output" window only and not to a console window, again in Debug mode only.

public class YourContext : DbContext
{	
	public YourContext()
	{
		Database.Log = sql => Debug.Write(sql);
	}
}

Solution 3 - C#

If you've got a .NET Core setup with a logger, then EF will log its queries to whichever output you want: debug output window, console, file, etc.

You merely need to configure the 'Information' log level in your appsettings. For instance, this has EF logging to the debug output window:

"Logging": {
  "PathFormat": "Logs/log-{Date}.txt",
  "IncludeScopes": false,
  "Debug": {
    "LogLevel": {
      "Default": "Information",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Console": {
    "LogLevel": {
      "Default": "Information",
      "System": "Warning",
      "Microsoft": "Warning"
    }
  },
  "File": {
    "LogLevel": {
      "Default": "Information",
      "System": "Warning",
      "Microsoft": "Warning"
    }
  },
  "LogLevel": {
    "Default": "Information",
    "System": "Warning",
    "Microsoft": "Warning"
  }
}

Solution 4 - C#

EF Core logging automatically integrates with the logging mechanisms of .NET Core. Example how it can be used to log to console:

public class SchoolContext : DbContext
{
    //static LoggerFactory object
    public static readonly ILoggerFactory loggerFactory = new LoggerFactory(new[] {
              new ConsoleLoggerProvider((_, __) => true, true)
        });

    //or
    // public static readonly ILoggerFactory loggerFactory  = new LoggerFactory().AddConsole((_,___) => true);
    
    public SchoolContext():base()
    {

    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseLoggerFactory(loggerFactory)  //tie-up DbContext with LoggerFactory object
            .EnableSensitiveDataLogging()  
            .UseSqlServer(@"Server=.\SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;");
    }
        
    public DbSet<Student> Students { get; set; }
}

If you would like to log to output window use this instead:

public static readonly ILoggerFactory loggerFactory = new LoggerFactory(new[] {
      new DebugLoggerProvider()
});

https://www.entityframeworktutorial.net/efcore/logging-in-entityframework-core.aspx

Solution 5 - C#

If someone is using EF6.1+ there is an easy way. Check the below links for more details.

https://docs.microsoft.com/en-us/ef/ef6/fundamentals/configuring/config-file#interceptors-ef61-onwards

Example Code

<interceptors>
  <interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
    <parameters>
      <parameter value="C:\Stuff\LogOutput.txt"/>
      <parameter value="true" type="System.Boolean"/>
    </parameters>
  </interceptor>
</interceptors>

Solution 6 - C#

Entity Framework Core 3

From this article

Create a factory and set the filter.

var loggerFactory = LoggerFactory.Create(builder =>
{
    builder
    .AddConsole((options) => { })
    .AddFilter((category, level) =>
        category == DbLoggerCategory.Database.Command.Name
        && level == LogLevel.Information);
});

Tell the DbContext to use the factory in the OnConfiguring method:

optionsBuilder.UseLoggerFactory(_loggerFactory);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPC.View Question on Stackoverflow
Solution 1 - C#AndrewView Answer on Stackoverflow
Solution 2 - C#Dennis MieszalaView Answer on Stackoverflow
Solution 3 - C#JayView Answer on Stackoverflow
Solution 4 - C#OgglasView Answer on Stackoverflow
Solution 5 - C#Kunal PanchalView Answer on Stackoverflow
Solution 6 - C#Christian FindlayView Answer on Stackoverflow