Entity Framework Logging Database Queries

Entity Framework starting from Version 6.0 allows us to log the commands & queries sent to the database. The Logging is done by using the DbContext.Database.Log property, which can be set to a delegate for any method that takes a string. All the actions performed by the Entity Framework is logged, which includes opening a connection, closing a connection, database initialization, Add, Edit, Insert & Select Queries, etc

Logging Database Operations

The simplest way to implement logging is to use the Console.Write Function. The console.write function takes a string as the parameter and writes that string into the console window. This makes it an ideal candidate to use for simple logging. All we need to do this is to assign the write method to DbContext.Database.Log property. The Example Code is shown below

Custom Logging

You can create a custom logging class and write the log to any place as you wish. You can write a log to a text file or to another database etc. The following code snippets show how to implement the custom logging

The code below EFLogger has a write method that accepts the string as a parameter. Inside the write method, we have sent the logs to the console. You can easily change it to any location of your choice.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top