TraceTool 9: The Swiss-Army knife of trace

A C#, C++, Delphi, ActiveX and Java trace framework and a trace viewer: Tail, outputDebugString, event log, and with Log4J, Log4Net, and Microsoft Enterprise Instrumentation Framework (EIF) support. This also comes with full support for Pocket PC development (C++ and DotNet).


The problem when debugging a multi-tier system (with perhaps multiple languages) is that traces are placed in different log files, in different formats, and in different locations on the network.

What is TraceTool

TraceTool overview

How it works

Traces are sent to the viewer using the WM_COPY_DATA Windows message, or using sockets (the ideal way to trace services, like ASP.NET). Currently, four frameworks are supported: .NET (C#), Delphi for Windows, Java, and C++. Java is a special case: only socket mode can be used for now, because 'pure' Java cannot send Windows messages directly.

Except for the C++ framework, traces are buffered in a message list and sent by another thread.

Before starting

The first thing to do before testing the client code is to run the viewer once, for self-registration. Put the viewer in the right place (in program files\TraceTool, for example) and run it. The viewer will add this icon on the tray bar:

It's not (yet) a COM server that registers interfaces and some rights, but writes the path to itself into the registry so that clients can launch it if necessary. Right click on this icon to show the following menu:

Click the "Show" item to display the viewer. You can also double click the icon on the tray bar.

Using the code

The framework is composed of three master classes:

See the TraceTool documentation (for the three languages), help file (.NET), or JavaDoc for a full description of the classes.

Sending traces is very easy; just use one of the three static members (Debug, Warning, or Error) of the TTrace class, and call one of the 'Send' methods. Each 'Send' method returns a TraceNode object that can be used to add sub traces.

TraceNode.Send method

Each trace is composed of two columns. The second column is optional. The following C# code shows different examples:

using TraceTool ;
TTrace.Error.Send ("Hello world") ;
TTrace.Warning.Send ("Hello" ,  "world") ;   
TraceNode Hello = TTrace.Debug.Send("Hello") ; // keep node reference
Hello.Send ("world") ;                         // use node to send sub trace

// or in one line :
TTrace.Debug.Send ("Hello").Send ("world") ;

It produces the following output:

Delphi sample:

uses TraceTool, 
TTrace.Warning.Send('hello' , 'world') ;

Java sample:

import TraceTool.* ; 
TTrace.Warning().Send("hello" , "world") ;

C++ sample:

#include "tracetool.h" 
TTrace::Debug()->Send ("Hello");

ActiveX sample (JScript):

var TTrace = new ActiveXObject("TraceToolCom.XTrace");
TTrace.Debug.Send("hello from jScript") ;

Tree indentation can also be done using the Indent and UnIndent functions:

TTrace.Debug.Indent ("Begin of procedure") ;
TTrace.Debug.Send ("inside procedure" ) ;
TTrace.Debug.Send ("Do some work" ) ;
TTrace.Debug.UnIndent ("end of procedure") ;

Multiple window tab

You can send traces in a separate window tab:

WinTrace myWinTrace ; 
myWinTrace = new WinTrace ("MyWINID", "My trace window"); 
myWinTrace.Debug.Send ("Hello", 
        "Can be used to store exceptions, for examples");

You can access the main WinTrace objects from the TTrace.WinTrace attribute.

The WinTrace API lets you save to a text file or an XML file, load XML files, and clear content. You can separate exceptions or SQL traces from classic traces, then save it at any time.

Each window can automatically save traces in an XML file at real time. To set the file name, you can use the WinTrace.SetLogFile function, or do it directly in the viewer. You can create a daily file (the date is appended to the file name) or disable the log file.

Multiple column traces

The original framework allows you to send two columns of information (including thread name, icon, and date). It's now possible to send as many columns as you want, but with a small restriction: multi-column is not supported in the main trace window, since many applications (and in different languages) cannot share the main window in "classic" mode and in "multi-column" mode. You must then create a window trace and set the column titles (with just a few lines). In that mode, of course, you lose the automatic thread name and date. You must send them yourself if you need to. Sending many columns of text is performed with the same API as for simple trace. Just add a tabulation ("\t" or char 9) between the different columns.

Here is a C# example:

WinTrace MultiColTrace ;
public  void initTrace()
     // create the window
     MultiColTrace = new WinTrace ("MCOL", 
                       "MultiCol trace window") ;

     // set the window to multi column mode. 
     // That automatically remove all columns
     MultiColTrace.SetMultiColumn () ;  
     // must be called before calling setColumnsTitle

     // add columns title
     MultiColTrace.SetColumnsTitle("col1 \t col2 \t col3");   
     // columns titles must separated by tabulations

     // change the active window (optional)
     MultiColTrace.DisplayWin() ;

Once initialized, use this new WinTrace instance to send data:

// columns data must separated by tabulations
MultiColTrace.Debug.send("1 \t 2 \t 3") ;

Info pane

The info panel displays additional information for a specific trace. When available, a small blue circle is visible on the gutter. This can be the object view, dump, stack, or any data that can be displayed in a maximum of three columns. The "Info" button on the toolbar shows or hides this panel.

SendObject and SendType methods

SendObject displays the object class information with the property values. SendType displays class information with static property values:

TTrace.Debug.SendType ("this type",  this.GetType() );
TTrace.Debug.SendObject ("this object", this );


If SendObject displays the complete structure of the object, with a lot of details, SendValue displays the object value (with multi-dimensional array and collections) on many levels. Primitives, and some classes like Date, are displayed as strings:

object obj;
obj = null;         
TTrace.Debug.SendValue ("null Object", obj);

obj = new Object(); 
TTrace.Debug.SendValue ("Object instance", obj);

obj = 123;          
TTrace.Debug.SendValue ("integer Object", obj);

obj = "str";        
TTrace.Debug.SendValue ("string", obj);

// simple array of Integer
int[] VtArr = new int[10]{7,1,5,2,0,3,4,8,6,9};
TTrace.Debug.SendValue ("simple array", VtArr);

Here is another screenshot for a complex multidimensional array with user defined bounds and types:

As you can see in the previous example, SendValue is not limited to a simple type. Object properties can point to another object. Recursive object display is limited, by default, to three levels. Object reference is displayed (class@code) on the second column. Objects already displayed are replaced by a "see @" reference. Presently, the Delphi SendValue is limited to variant values (no properties) and arrays.


SenDump displays the buffer dump. Sample code:

	TTrace.Debug.SendDump ("Dump test", "Unicode", 
	   System.Text.Encoding.Unicode.GetBytes(str) ,50) ;


	TTrace.Debug.SendBitmap("Bitmap", pictureBox1.Image);


	nodeEx.AddXML(" Hello XML ");


SendTable and AddTable send multicolumn table in the info panel :

// create the table
TraceTable table = new TraceTable();

// add titles. Individual or multiple columns titles 
// can be added, separated by tabs
table.AddColumnTitle("colA");          // first column title
table.AddColumnTitle("colB");          // second column title
table.AddColumnTitle("title column C\tcolD");  // other columns title

// add first line. Individual or multiple columns data 
// can be added columns, separated by tabs
// add first col
// then add other columns (tab separated)
table.AddRowData("b" + "\t" + "c" + "\t" + "d" + "\t" + "e");            

// add second line
// add all columns data in a single step (tab separated)
table.AddRowData("aa" + "\t" + "data second column" + 
                 "\t" + "cc" + "\t" + "dd" + "\t" + "ee");  

// finally send the table
TTrace.Debug.SendTable("Mytable", table);

SendStack and SendCaller functions

Sendstack and SendCaller let you display the stack information:

TTrace.Debug.SendStack  ("Stack test" , 0) ;
TTrace.Debug.SendCaller ("Caller test" , 0) ;

Resendxxx and Appendxxx functions

Once a node is sent, you have the possibility to change the text. For example, send the "Start.." text, and when an operation is completed, append the "Done" text, or replace one of the two columns with a new text:

TraceNode start1 = TTrace.Debug.Send ("Start 1 ..") ;
start1.ResendRight ("Done") ;

TraceNode start2 = TTrace.Debug.Send ("Start 2 ..") ;
start2.AppendLeft ("Done") ;

Note that the time is not changed.


If you want to follow the values of a variable, you can send it using the classic TTrace.Debug.Send method, but that can produce a lot of traces. In its place, you can use the TTrace.Watches.Send method that shows only the last value. Watches are displayed on a separate window. You can create different watch windows.

TraceNodeEx: A more easier way to create complex traces

In place of overloading the Send method with different parameters, you can use the TraceNodeEx class (that inherits from TraceNode). The advantage is that you can have, for example, many dumps for the same trace, on the "Info" pane. The SendObject, SendType, SendValue, SendDump, SendStack, and the SendCaller functions have the Addxxx counterparts.

You must specify the parent node trace in the constructor parameter. The parent IconIndex, Enabled, and Id properties are used for the newly created trace (a null parent is also accepted).

You can specify the text of the columns separately, specify the icon to use, add object and type, or add Dump to the associated 'Detail' tree. When the node is completed, just call its Send method:

// Create an unicode string with special 
// char in front and at the end.
string str =  '\u2250' + "azertyuiop qsdfghjklm" + '\u9999' ; 
// Create a trace node with the same icon and 
// Enabled properties as TTrace.Debug
TraceNodeEx node = new TraceNodeEx (TTrace.Debug) ;

// Fill it
node.LeftMsg = "hello" ;
node.RightMsg = "world" ;
node.IconIndex = 8 ;
node.AddDump (
   System.Text.Encoding.Unicode.GetBytes(str) ,50) ; 
node.AddDump (
   System.Text.Encoding.ASCII.GetBytes(str) ,50) ;   
node.AddObject (str) ;

// and finally send it
node.Send () ;

The TracenodeEx.Resend function lets you resend the two texts (not members) at any time.

Pocket PC development

The TraceTool API is now compatible with Pocket PC. You can either develop in C++ or in C#. Both Compact Frameworks 1 and 2 are supported. See the demos for Visual C++ 4, Visual Studio 2003 and 2005.

Other trace framework support

The TraceTool API can be used with other libraries:

A bridge is provided for all these famous frameworks. See the TraceTool overview diagram on the top of this document.

System.Trace (.NET) support

The classic Microsoft "Trace" can be redirected to the viewer using the TTraceListener bridge. Here is a sample:

Trace.Listeners.Clear() ;
Trace.Listeners.Add (new TTraceListener ()) ;

int[] myArray = new int[3] { 3, 5 , 5};     
Trace.WriteLine ("TraceListener demo") ;
Trace.Write ("myArray : ") ;
Trace.WriteLine (myArray) ;

That works fine, of course, but you lose abilities to display object information, array values, dumps, stack, ...

Microsoft Enterprise Framework (.NET) support

Microsoft Enterprise Framework (EIF) traces can be redirected to the viewer using the TraceToolEventSink library.

Sample EIF demo:

private static EventSource myEventSource = 
                           new EventSource("EIFDemo");

static void Main(string[] args) {
   // sample 1 : use static ErrorMessageEvent
   // msg, severity, error code
   ErrorMessageEvent.Raise("Error Message Event", 1, "CODE");   

   // sample 2 : create a Trace Message Event instance, 
   // fill it then raise from the event source
   TraceMessageEvent messageEvent1  = new TraceMessageEvent();
   messageEvent1.Message = "Costly Message";
   myEventSource.Raise(messageEvent1 );

   // sample 3 : static one line (which wraps the 
   // above code sequence)
                        "Static One Line Message");

   // sample 4 : static one line which is raised through 
   // the EventSource.Application EventSource.
   TraceMessageEvent.Raise("Static One Line Message " + 
                   "through the Application event source");

EIF uses a specific configuration file to link traces to the target library (event log, SQL, ...). See the demo configuration file for more details on TraceToolEventSink. Note that this library must be signed (not the case of Log4Net support).

Log4Net (.NET) support

Log4Net traces can be redirected to the viewer using the TraceTool4Log4Net library (TraceTool for Log4Net). Column formatting is done by Log4Net, but tabulations must be used as column separators. Column title must be specified in the CONFIG file.

Sample Log4Net demo:

// Create a logger for use in this class 
// (Log4NetDemo.Form1)
private static ILog log = LogManager.GetLogger(

private void butLog_Click(object sender, EventArgs e)
   // simple test
   log.Info("Hello world");

   // use an object as message (the object is 
   // displayed in the info panel)

   // exception test (the exception is displayed 
   // in the info panel)
   Exception MyException = new Exception("my exception") ;
   log.Error("Received exception",MyException);    

Like for EIF, the Log4Net engine, the configuration file is used to link traces to the library.

Log4J (Java) support

As for Log4NET, Log4J traces can be redirected to the viewer using the TraceTool library. Column formatting is done by Log4J, but tabulations must be used as column separators. Column title must be specified in the CONFIG file.

Sample Log4J demo:

Logger logger ;    // Log4J logger
Category cat ;     // Log4J category

// Initialize Log4J 
logger = Logger.getLogger("");  
cat    = Category.getInstance(JavaDemo.class);

// simple logger test. Log4J will prepare the trace 
// and call the TraceTool appender."Hello world");

// Logger test with attached exception (displayed in info pane)
Exception  e = new Exception("my exception") ;
logger.debug("Received exception",e);
// Category test with object value (displayed in info pane)

PropertyConfigurator.configure opens the configuration file to know how to link traces to the library. Unlike the .NET support, the TraceTool Log4JAppender class doesn't need to be implemented in another library (Jar).

Gdebug (Delphi) support

Since the original idea of TraceTool comes from the Gdebug tool, I also provide a DbugIntf.pas file with the same functions. That helps those users switching from Gdebug to TraceTool.

Sample Delphi code:

SendDebug ('Hello world') ;
SendDebugEx ('Hello world', mtWarning);

Pocket PC development

The C++ Framework works with classic C++ applications (like MFC) as well as with Pocket PC projects. The socket mode is used in this case. The traces are sent to the viewer in the development PC. The C# Framework is not yet compatible with the Compact Framework (should be done in the next release).

Console applications

The four frameworks can also be used for console applications. See the TTPipe demo from Michael Kramer in the .NET samples. This console application redirects the console output to the viewer, using the '|' pipe redirector:

YourProg | TTPIPE [-t TabName] [-i Viewer Host IP Address] [-p Viewer Port]

Tracing ASP.NET

The problem with ASP.NET is that pages run under a service (IIS). The ASP code is then confined inside the service, and cannot send Windows messages to another process. The only way here is to use the second door: socket. You just need to modify the SendMode property of the TTrace.Options to SendMode.Socket. You can do that in the Page_Load, or before any Send method:

private void Page_Load(object sender, System.EventArgs e)
    TTrace.Options.SendMode = SendMode.Socket ;
    TTrace.Debug.Send (
        "Page_Load " + Convert.ToString(TTrace.TraceCount));

Important: In socket mode, the viewer must be launched manually. In Windows message mode, the client framework runs the viewer itself.

The TTrace.TraceCount is a static integer that is incremented each time a trace is put in the buffer. TraceCount is used only for test. Note: This is not the actual number of messages sent!

You can also modify the machine.config or web.config to include a custom HttpModule, and in the Init() method, set the socket mode. The number of active socket connections (.NET, Java, or Delphi) to the viewer is displayed in the status bar at the left (blank at start).

To facilitate ASP.NET configuration, it's better to use one of the configuration files.

.NET configuration

Configuration of the TraceTool client application can be done in a few ways:

Sample App.config file:

      <section name="TraceTool" 
         type="TraceTool.ConfigSectionHandler, TraceTool" />
      <param name="SendMode" value="winmsg" />
      <Param name="sockethost" value="localhost" />
      <param Name="SendProcessName" Value="false" />
         <param name="Enabled" value="true" />
         <param name="IconIndex" value="24" />


You can extend the TraceTool functionality with plug-ins. Plug-ins can be written in .NET, Delphi, or C++. With plug-ins, you can add, for example, a key logger, registry logger, or a protocol analyser to TraceTool without having to create a separate application. Plug-ins receive user actions, like deleting a node, pushing the clear button, or trying to close a trace window. Plug-ins can add actions on the viewer menu, or labels and buttons on a trace window. A functional clipboard history is included in the main distribution. The plug-ins must be added in the viewer using the View / Options menu.

Using the viewer

TraceTool is more a tool to debug an application than perform logs, due to its 'visual' nature. You can, however, save the content to a file (text or XML), select nodes, delete them, or copy to the clipboard. See the Options dialog box to modify the way the clipboard is filled. Another interesting option is the possibility to delete old traces, keeping, for example, 2000 nodes (on the root). See the same dialog box to modify the Max and Min.

Catch system OutputDebugString messages

To display the OutputDebugString windows, activate it in the window menu (show OutputDebugString). The OutputDebugString windows can be paused or cleared using the toolbar. You can also copy selected lines to the clipboard and save the content to an XML file (the same format as the TraceTool export).

Display multiple 'Tail' content files

To add a new "Tail" tab, select the Windows/Open Tail File... menu, then select the file you want to watch.

Clipboard operations are allowed, but not export, since traces are already stored in a file. The number of displayed lines is also specified in the Options menu.

Watch live event log traces (application, security, system, or other)

To add a new "event log" tab, select the Windows/Open Event Log... menu, then select the log you want to watch. New events are automatically added.

Clipboard operations and XML export are allowed (the same format as TraceTool export).

Load saved XML file

You can save traces send by the framework, the OutputDebugString window, or the Event Log window to an XML file, using the viewer or the API (framework windows only). You can then reload on your development PC, traces from a production environment. To open the "Saved XML trace" tab, select the Windows/Open XML traces... menu, then select the file you want to watch.

License information

You are free to distribute the viewer (GPL) and to incorporate the library (LGPL) in your product (commercial or not).

The only thing you can't do is to sell the viewer (or a modified version) and the API as a tracing solution.

Points of interest

For those who want to have some examples on how to use the .NET refection API, the TraceNode.cs and the reflections.cs files contain all the information you'd need, for example, how to know if a method is static, virtual, or declared in an interface. Same for Java and Delphi reflection. The viewer source code shows how to dynamically load and unload .NET assemblies and Java classes. See the same source if you are interested in learning how to use the Java Native Interface (JNI) from a Delphi application.

Future improvements



Framework sources and demo for Dot net, Java , C++ and Delphi, the Viewer and his code are on Logo