Log the SQL generated by Entity Framework
Here's a common example of what you do:
Context.Database.Log = Console.Write
..where Context
is a DbContext
.
.Log
is of type Action<string>
-- so you can set it to any method that returns nothing and has 1 parameter, a string.
Contextual help on ".Log" read:
Summary:
Set this property to log the SQL generated by the
System.Data.Entity.DbContext
to the given delegate. For example, to log to the console, set this property toSystem.Console.Write(System.String)
.
First thing I tried was setting it to Debug.WriteLine
... but this is not good because Debug.WriteLine is "Conditional" -- and only exists if the "DEBUG" compilation symbol is defined. Here is how Debug.WriteLine
is defined:
[Conditional("DEBUG")]
public static void WriteLine(string message);
I thought I could get around it like this:
#if DEBUG
Context.Database.Log = Debug.WriteLine;
#endif
...but no, same problem.
Instead I had to do this... create a new "Write" method, that is a wrapper to Debug.WriteLine
private void Write(string message)
{
Debug.WriteLine($"** {DateTime.Now:yyyy-MM-dd HH:mm:ss} **: {message}");
}
Then I can assign Log to the wrapper function.... I still put it in a conditional because that's the whole point in this case...
#if DEBUG
Context.Database.Log = Write;
#endif
I also created a helper method to enable it from outside the scope where Context
is available:
public void EnableSqlLogging(bool logit, Action<string> loggingEndpoint = null)
{
if (logit)
{
Context.Database.Log = loggingEndpoint ?? Write;
}
else
{
Context.Database.Log = null;
}
}