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?
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 anyTextWriter
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: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:
EF Core logging automatically integrates with the logging mechanisms of .NET Core. Example how it can be used to log to console:
If you would like to log to output window use this instead:
https://www.entityframeworktutorial.net/efcore/logging-in-entityframework-core.aspx
You can use this line to log only to the "Output" window and not to a console window, again in Debug mode only.