class LogUtil<T> : ILogUtility
{
log4net.ILog log;
public LogUtil()
{
log = log4net.LogManager.GetLogger(typeof(T).FullName);
}
public void Log(LogType logtype, string message)
{
Console.WriteLine("logging coming from class {0} - message {1} " , typeof(T).FullName, message);
}
}
public class Logger
{
ILogUtility _logutility;
public Logger(ILogUtility logutility)
{
_logutility = logutility;
}
public void Log(LogType logtype, string message)
{
_logutility.Log(logtype, message);
}
}
I need to have the functionality to be flexible and have the ability to remove the LogUtil class in the future and use some thing else.
So I write LoggerUtility wrapper class as follows:
class LoggerUtility<T>
{
Logger logger;
public LoggerUtility()
{
LogUtil<T> logutil = new LogUtil<T>();
logger = new Logger(logutil);
}
public void Log(LogType logtype, string message)
{
logger.Log(logtype, message);
}
}
My client code as follows:
public class TestCode
{
public void test()
{
new LoggerUtility<TestCode>().Log(LogType.Info, "hello world");
}
}
To get loose coupling from LogUtil, I end up writing 2 wrapper classes Logger and LoggerUtility. So in the future, if I have to add another method
in the ILogUtility, I would have to add that method to Logger class and then LoggerUtility.
What is the best way to write LoggerUtility so that I could write the client code as follows:
new LoggerUtility<TestCode>().Log(LogType.Info, "hello world");
Please let me know.
Thanks
It looks like you’re adding a level of abstraction where there really doesn’t need to be one.
If we start with your end result, LoggerUtility just needs to have an interface that it can use to log things based on the
LogTypeparameter.Your
Loggerclass, as its currently written, is just a thin wrapper around theILogUtilityinterface. So why bother adding that layer? Why can’t theLoggerclass use anILogUtilityinstance directly? You could even go one step further and define your interface asILogUtility<T>and know that when you create aLoggerUtility<Foo>that the instance of the logger it will use will be based on the Foo class.But honestly, I think you may just be reinventing the wheel here. Take a look at Common Logging for .NET. It will probably ease what you’re trying to do and make more sense in the long run.