Entity Framework Code First Logging
Glimpse
Glimpse has EF plugins for profiling for all versions of EF
Logging (EF 6+)
EF 6 (Oct 2013+) has logging support. dbContext.Database.Log takes an Action<string>
dbContext.Database.Log = s => Trace.TraceInformation(s);
You can set this in the dbContext ctor.
For more control, use the static DbInterception to add an IDbInterceptor.
DbInterception.Add(new LoggingCommandInterceptor());
Or using a DbConfiguration in the same assembly as the DbContext
public class AppConfig : DbConfiguration
{
public AppConfig()
{
AddInterceptor(new LoggingCommandInterceptor());
}
}
IDbInterceptor is an empty interface, so you really want to implement IDbCommandInterceptor
public class LoggingCommandInterceptor : IDbCommandInterceptor
{
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
Trace.TraceInformation(command.CommandText);
}
public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
if (interceptionContext.Exception != null)
Trace.TraceError(command.CommandText + " errored " + interceptionContext.Exception);
}
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
Trace.TraceInformation(command.CommandText);
}
public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
if (interceptionContext.Exception != null)
Trace.TraceError(command.CommandText + " errored " + interceptionContext.Exception);
}
public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
Trace.TraceInformation(command.CommandText);
}
public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
if (interceptionContext.Exception != null)
Trace.TraceError(command.CommandText + " errored " + interceptionContext.Exception);
}
}
Logging (pre EF 6)
Pre EF 6, I used EF Provider wrappers (with bug fixes) which worked well.
My blog entry on using using the EF provider wrappers for SQL logging a DbContext.