Log Queries executed by Entity Framework DbContext
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"
}
}
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...
}
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);
}
}