Simple Logging is a new feature of Entity Framework Core and it was introduced in EF Core 5. As the name suggests, it is very simple to enable this type of logging. It does not even need any additional NuGet packages. In this article, let’s try to discuss how it can be enabled and configured.
Logging is very useful during development and debugging of the application. This logging can help you understand how the LINQ syntax is getting converted into SQL queries and it would also provide more insights about how much time taken by an individual SQL query.
This logging can also be used to analyze how application issues SQL commands and if the interaction of application and datastore can be further optimized.
There are two places to configure this method:
- Override OnConfiguring method in DbContext implementation
- Provide options while configuring DbContext in
Below code example shows both ways.
Redirecting Log Output
As discussed earlier, LogTo method takes an action delegate. It expects a method which takes string as parameter. This Action delegate can then write logs to intended data store.
So, the log output can be redirected to
- Console by passing Console.WriteLine to LogTo method.
- OR logs can be written to the Debug console, by using Debug.WriteLine
- OR logs can also be stored in a file by using StreamWriter class.
- OR logs can be stored to database by using custom logger.
Below code example shows how to redirect log output to a file. Note that this is just a demo code and should be reviewed carefully, before using this for real world applications.
Below snapshots shows the resulting log file. Below snapshots also shows that a command took 34ms to execute the command. it also shows the command which was executed.
Enable Detailed Errors
One of the common debugging scenario is data type mismatch. Let’s say database is returning
NULL and the EF core model definition does not allow
NULLs. This may cause runtime errors. This is same situation as explained in this question on StackOverflow.
To debug such information you can call EnableDetailedErrors method. If this method is called, EF core wraps every database call inside a
I hope you find this information useful. Let me know your thoughts.