Monday, November 14, 2011

NLog Network Target

Recently at work, I'd been tasked with utilizing NLog's targeting system to dump data into our system.  NLog itself has been working really well for us, but the downside is that the documentation leaves a lot to be desired.  Furthermore, examples and samples are extremely limited.

So, how in the world do we utilize this?

My first thought was to tear everything open in .NET Reflector (ILSpy, since I can't find a free copy of .NET Reflector anymore) and then work to understand how it works.

The targets we were most interested in were the Network and Memory targets -- such that we could grab data that was being logged and then further process it.  Why not have our complex-event processing system also process logs as well?  A self-logging system.  Hell, why not?  Also, doing what your boss asks is generally a good way to stay employed.

The Network Target

So, the network target.  It handles several different variations of address -- UDP, TCP, variations of IP4/6.

The standard attack pattern for this is actually pretty much the same as any other TCP/UDP application.  Manage your clients (if necessary) and then process the data.

The only difference is that handling the data is different.  The chart above shows the general jist.

  1. When reading from the socket, convert your incoming data to a string.
  2. Ensure that it is decoded properly -- by default, your message will be in UTF8.
  3. Store message in a buffer.
  4. Scan for end of line characters and process as necessary.
It's pretty simple.  A very simple handler would look like the following:

  string incomingMessage = UTF8Encoding.ASCII.GetString(incomingSocketBuffer, 0, incomingLength);
  //Process and analyze for "\r\n"

Not bad, eh?  The above code assumes that incomingSocketBuffer is what was received from the Socket's Receive method, and the incomingLength is the length of what was received.  incomingStringBuffer is a StringBuilder that I use to store up the data.

Of course, there are much better ways of handling this, but this is the most simplistic and hopefully it demystifies NLog's Network target.