Tuesday, August 22, 2017

log4net UDP Listener

There are lots of articles online about how to write a UDP listener client for logging broadcasts from the log4net UdpAppender. Unfortunately, most of them use localhost, or hard-coded addresses and port numbers and are misleadingly trivial and not good guidance for realistic use.

In my realistic scenario there are dozens of applications of various types running on two servers in an office network, and all the log4net sections of the config files specify:

<remoteAddress value="224.9.9.9"/>
<remotePort value="9999"/>

The address 224.9.9.9 is in the global multicast address scope so anyone within the broadcast horizon can listen-in.

But exactly how can a .NET listener client application somewhere on the local network listen to the logging broadcasts from the server machines? I fumbled around for a while getting no broadcasts because I didn't realise you had to "join" the multicast group. When I saw the JoinMulticastGroup method in the MSDN documentation I suddenly uncovered the missing link to make my C# code work. In skeleton form the required code is like the following.

var ep = new IPEndPoint(IPAddress.Any, 9999);
var client = new UdpClient(ep);
client.JoinMulticastGroup(IPAddress.Parse("224.9.9.9"));
while(true)
{
  UdpReceiveResult result = await client.ReceiveAsync();
}

Put the ReceiveAsync in a loop that suits your coding style. There is no elegant way to detect when a client is closed to end your loop. Some part of your code will call client.Close() and the await in the loop will throw an ObjectDisposedException. As far as I can tell, catching that specific Exception and breaking out of the loop is the neatest thing you can do.

No comments:

Post a Comment