Essentially, you create an interface, and then a specific implementation of that interface, which directly transfers the Log4net classes and methods. Additional registration systems can be wrapped by creating more specific classes that combine other classes and methods of these systems. Finally, use factory to instantiate your wrappers based on configuration settings or a line of code change. (Note: you can become more flexible and complex - using an Inversion of Control container, such as StructureMap .)
public interface ILogger { void Debug(object message); bool IsDebugEnabled { get; } // continue for all methods like Error, Fatal ... } public class Log4NetWrapper : ILogger { private readonly log4net.ILog _logger; public Log4NetWrapper(Type type) { _logger = log4net.LogManager.GetLogger(type); } public void Debug(object message) { _logger.Debug(message); } public bool IsDebugEnabled { get { return _logger.IsDebugEnabled; } } // complete ILogger interface implementation } public static class LogManager { public static ILogger GetLogger(Type type) { // if configuration file says log4net... return new Log4NetWrapper(type); // if it says Joe Logger... // return new JoesLoggerWrapper(type); } }
And an example of using this code in your classes (declared as readonly static field):
private static readonly ILogger _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
You can get the same effect that is more powerful:
private static readonly ILogger _logger = LogManager.GetLogger(typeof(YourTypeName));
The first example is considered more maintainable.
You do not want to create a Singleton to handle all protocols, because Log4Net logs are logged for the calling type; its much cleaner and more useful so that each type uses its own logger, rather than just seeing one type in the log file reporting all messages.
Since your implementation should be reusable enough (other projects in your organization), you can make it your own assembly or, ideally, include it in your own assembly / assembly / assembly. Do not redefine classes separately in each of your business / data / user interface assemblies that are not supported.
cfeduke Oct 03 '08 at 11:49 2008-10-03 11:49
source share