Thursday, April 12, 2012

Creating Custom NLog target

I have started to use NLog and am currently exploring its features.  One of the features that I was looking at was to capture all that is being logged by various classes in different parts of the application. I wanted to display the logging in a window in a WPF application. After reading the docs, it came down to writing a custom target for NLog. In this post, I am going to create a NLog target in an assembly and let NLog know to load/create the target from that assembly.

Step 1:

Declare the target in nlog section of the config file and use it in Target section. In the snippet below, NLogSample is name of my executable where the target is implemented. NLog uses reflection and looks for Target attribute in the assembly to add targets to its internal collection. All this happens before the application starts to use the logging features of NLog:

Step 2:
Create the target in code. Here I am simply letting the clients register (I am using Rx, you can use Events) and this target informs the clients of the new message. NLog does offer MemoryTarget class; however that class does not expose any event to capture the message that was written. This target provides that functionality:

Step 3:
Now you can use the target in code to capture the messages from it. To get the target from NLog, you can do the following:

Once we have the target, we can subscribe to the event and use it. Here I am adding it to an observablecollection, which is bound to a listbox in WPF:

Following shows the log captured by the collection and shown in the window. For the sample, I am logging each resize event of the window. When you run the application(link at the bottom), you will also get a log in the Logs folder of the application. Any message that is logged after the listbox is bound, will appear in the log and the window.


Links/Code:
How to write a NLog target
Sample Code at Github can be downloaded from here. Code includes NLog and Reactive assemblies used in the sample. Its uses VS2010, .Net 4.0, C# and you should be able to build/run the sample if you have VS2010 or above.

1 comment:

  1. Hi,

    Nice sample. I tried to do the same with silverlight and got errors everywhere. It seems, wpf and silverlight are not truly compatible. some of the errors i get
    1. style.triggers are not available on silverlight. afaik, no direct alternatives.
    2. DependencyProperty.Register no compatible overloads
    3. BindingOperations.ClearBinding does not exist in silverlight

    these are some of the errors that i remember on top of my head. i tried fix it myself but have been unsuccessfull. i would appreciate your assist. plus, patch for nlog to support listbox in silverlight would be very helpful for a lot of people.

    thansk.

    ReplyDelete