Log Queries executed by Entity Framework DbContext

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 = s => System.Diagnostics.Debug.WriteLine(s);

    // Your code here...
}

UPDATE 2022: Logging is now enabled by default in development in ef core. The behavior can be configured in the builder of your DB Context (enable sensitive data logging to log the query parameter values or specify events to be logged ):

      services.AddDbContext<IDbContext, ApplicationDbContext>(
        options => options.UseSqlServer(dbConnectionString)
                          .LogTo(s => System.Diagnostics.Debug.WriteLine(s))
                          .EnableDetailedErrors(isDebugMode)
                          .EnableSensitiveDataLogging(isDebugMode));

or you can use the app.settings file to define logging configuration for events of your interest

Leave a Comment