Configurable Change Log in Entity Framework Core

Emre Ceylan
2 min readJan 27, 2020

--

In this story, I will talk about a solution that helps you to log your data change logs to any data source in a configurable way. We will do our process at dbcontext level so any repository pattern will work with this.

So what we will do is, storing the table and field names that we want to log, look for the changes on change tracker of ef core and check with these table and field definitions. Change tracker class is responsible for tracking the state of each entity retrieved using the same dbcontext instance. It gives us the details about states like added, modified, deleted, unchanged and detached. And also it gives the property and class definitions, old and new values of modified entity. In this example we will look for only modified entities to log.

Firstly, in a table we store the definitions of which tables and columns we want log. You can also create a UI for this setting and let anyone choose which ones to log or not. After this step we can get these definitions and use it in dbcontext code to track and check changes. In my own implementations, I prefer to cache these definitions and not to ask my data source in every operation.

We now write the code that we need for tracking and checking changes. For this we will override the save methods of dbcontext and inject our method before save change is completed.

So lets look at the details of our logging process.

We are getting the log definitions from cache, and use it in our collect changes method. So collect changes method is the main method of our work. Here are the details of it;

We are getting user id and username from httpcontext if authentication is used. Then we ask change tracker class for modified entities and loop through these entities. We get the table name of entity and check if our log definitions have this table enabled. If yes then we can check and compare the changed properties of this entity. Finally we can get the old and new values of modified entity and return a list of models that we will log with the related properties. You can store these logs on any database provider. In my example, I am storing these logs on Elasticsearch. You can find the detailed example on my github repo as follows.

--

--