Logging Tools

CavemanTools doesn't implement a logging system, but offers a few helpers to make you more productive in that area. Nothing complex or fancy, just tiny bits of usefulness.

Example
//can be null. Implementation can act as an adapter for log4net, elmah etc
public ILogWriter Log { get; set; }
		
public void SomeMethod()
{
	Log.Write(LogLevel.Debug,"debugging info"); //extension method, no need to check for null
}

Discussion
When adding logging capabilities to a class, you'll want to inject the logger via constructor or property. However it's cumbersome to do that for every object where you want that (yes, I know about IoC, that's not the case here) and besides that you might want to use it only when developing. So you can use a singleton (which everybody knows is bad :D ) or a dependency property. In this example the latter approach is used. Just define the property, supply an implementation for ILogWriter (an adapter for the logging library you like) and call the extension method Write() .

Setup
public class MyClass
{
public ILogWriter Log { get; set; }
		
public void SomeMethod()
{
	Log.Write(LogLevel.Debug,"debugging info"); 
}
}

Case1
var c= new MyClass();
c.SomeMethod(); //nothing happens, no exception is thrown

Case2
var c= new MyClass(){ Log = new DebugLogWriter()};
c.SomeMethod(); //"debugging info" is sent to VS debug window
DebugLogWriter is an implementation of ILogWriter which can be used to send messages to VS debug window (it's basically an adapter for System.Diagnostic.Debug)

Last edited Jan 21, 2011 at 1:14 PM by mike_sapiens, version 4

Comments

No comments yet.