Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A TraceListener that sends messages via UDP

0.00/5 (No votes)
28 Jul 2004 1  
An implementation of a TraceListener that sends messages across the network.

Introduction

Generating application log messages is important for diagnosing and testing a system, and a must for complex and large systems. .NET framework currently provides EventLogTraceListener and TextWriterTraceListener, which work fine for desktop applications; but for more complex server applications which need to be monitored/tested remotely, there is no solution.

Hence, I wrote this small utility NetTraceListener class that extends from TraceListener and outputs log messages to a defined UDP port.

Requirement

You would require a basic UDP notes collector to see the UDP messages.

Code

The entire source file is written in less than 20 lines of code.

The constructor takes a host name (e.g., "127.0.0.1") and a port number, it creates a UDPClient object that is used to send UDP messages.

UdpClient notifier; 
IPEndPoint groupEP; 
public TraceNetListener( string host, int port ) 
{
 groupEP = new IPEndPoint( IPAddress.Parse( host ) ,port );
 notifier = new UdpClient(); 
}

The overridden method Close():

public override void Close() 
{ 
    notifier.Close(); 
    base.Close ();
}

The overridden method Write(), it converts the supplied message into bytes, and sends them over a UDP channel.

public override void Write(string message) 
{
 try 
 {
  byte[] bytes = Encoding.ASCII.GetBytes(message);
  notifier.Send(bytes, bytes.Length, groupEP);
 } 
 catch (Exception e) 
 {} 
}

Now in your main application, you need to add this class as a trace listener.

Trace.Listeners.Add( new TraceNetListener("127.0.0.1", 11000 )); 
Trace.Write("HELLO WORLD !");

And you are all set. When you execute this code, your UDP NoteCollector will get all your trace messages.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here