C# Strategy Design Pattern Example — Multiple Logging Sources

Nemanja Petrovic
2 min readJan 18, 2018

I would like to talk about logging information from user activity, exceptions, errors, and performance of the systems. I work in a company which is building an enterprise hosting platform offering automation-billing-provisioning solutions and through my work there I found out how much logging is important in enterprise systems.

In this article, I will show you a simple way to implement multiple logging sources by using Strategy design pattern. Let’s start by defining an example of logging sources:

  • Audit Log — to log an event information and the time the event occurred, example: Customer terminated his subscription, customer created a new article and etc…
  • Exception log — to log all exceptions that occurred during the execution of the code
  • File log — to log additional information inside files

For all of these logging sources we will create a separate class which inherits an interface with a simple function void Log(string logMsg);

First, let’s create an interface with a name ILogType and a simple function we already mentioned:

Now we are going to implement all types of logging sources:

AuditLog, DatabaseLog and FileLog:

After we have done this implementation it’s now time to create strategy class like in the next example:

We did all the things required to implement Strategy design pattern. Now it only remains to create instances and call functions:

This will print in a console:

File Strategy:
File Log Message: file log data
Database Strategy:
Database Log Message: database log data
AuditLog Strategy:
Audit Log Message: audit log data

And that’s it, it’s a basic example of Strategy design pattern usage which covers up multiple behaviors of related classes. You can check out the whole code in a GitHub repository.

Let’s follow up on Twitter and LinkedIn.

--

--