Adapter Design Pattern with logging in C#
Adapter design pattern is a structural design pattern that provides two unrelated interfaces to work together. The most common illustration of adapter design pattern is sockets from different countries. Well most of us faced with laptop adapter issues when traveling, and looked for appropriate adapter for our laptops. So, by using an adapter we are able to plug our laptop chargers to sockets. Or using a card reader to plug our memory card from our camera to our computer. Thus, we make two unrelated interfaces to work together. The elements of adapter design pattern are Client, Target, Adapter and Adaptee. We can see the Gang of Four definition for ADP, and description of each element of it below;
Convert the interface of class into another interface clients expect.Adapter lets class work together that couldn’t otherwise because of incompatible interfaces.
A real-world example to implement an adapter pattern is logging in dotnet, logging in dotnet is not more effective for memory let’s use our example and see how to use an adapter design pattern to solve our problem
We create loggerFactory whose default logging level is Information in this case when we log information like in our example logging user age it will convert the Age (int) to an object and convert a value type to reference type (boxing) this will add heavy on GC, but this is normally way if the default log level is information and I log info but what I make the default log level is warning and this will not show the info message but will convert Age to object and add a lot of data I don’t need it, and be attention the implementation of LogInformation of dotnet this will allocate 417 B without I need it.
so what I need to make is to make another generic method when I log to accept the type of arg instead of an object and also check the log level is enabled before passing arg to LogInformation. the adapter pattern will help to add new logic on top of the implementation of dotnet.
so we will update our to use our logging adapter instead of
this will improve our performance and not convert our value type to a reference type (boxing) in the case we don’t need to convert when the log level is not enabled.
source code GitHub. Be attention that you don’t have to do this implementation if you using Serilog package it implements this behavior.