Last Updated: June 29, 2017
·
10.91K
· esskar

Use C# magic to turn any class into log-aware class

Does this code look familiar to you?

namespace MyNamespace
{
    public class MyClass
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
    }
}

In order to create a logger, you have to access a static LogManager that returns a logger for your class. This will leave boring and reapeating code everywhere and pretty much the same for any logging framework out there.

One could say: Not in my case, i have a base class for that - that may look like this

namespace MyNamespace
{
    public class MyBase
    {
        public Logger GetLogger()
        {
            return LogManager.GetLogger(this.GetType());
        }
    }
}

This helps for some cases where you control the base class. But what if you need to derive from third party class? Well, then you are most likely back to the static approach.

What if I tell you, that this is about to change?

Let's look at the following piece of code

public interface ILogAware { }

Well, this does not look exciting, does it? It looks more like nothing.
But what if I add the following code?

public static LogAwareExtensions 
{
    public static void LogDebug(this ILogAware logAware, string format, params object[] args)
    {
        var logger = LogManager.GetLogger(logAware.GetType());
        logger.Debug(format, args);
    }
}

Suddenly, we turned nothing into a powerful tool that adds logging capability to any of your classes just by implementing ILogAware - an empty interface - so nothing has to be implemented at all.

That's what i call c# magic.

I hope that helps!

1 Response
Add your response

over 1 year ago ·