Thursday, June 9, 2011

Creating Awesome Logging Control with NLog, WPF, C# and Memory Target

First we need to define new "reactive" memory target. This target will notify us when some log item is received in memory.

Code Snippet

using System;

using NLog;

using NLog.Targets;

namespace VWBT.Controls.Log

{

publicclassMemoryEventTarget : Target

{

publiceventAction<LogEventInfo> EventReceived;

///<summary>

/// Notifies listeners about new event

///</summary>

///<param name="logEvent">The logging event.</param>

protectedoverridevoid Write(LogEventInfo logEvent)

{

if (EventReceived != null) {

EventReceived(logEvent);

}

}

}

}

Now we are ready to define our logging control. We will keep last 50 log messages in the ObservableColection, which we will bind to the ListView control. We also register event for our memory target inwhich we update our collection.

5 comments:

Hi,I've managed to make it work now but I have another problem. Once I use your setup, I lose all the other setup I've made in the NLog.conf, would there be a way to keep these?Thanks for this awesome control!Laurent