Wednesday, August 8, 2007

Trace in .NET

I'm adding trace functionality to a project and I had almost forgotten System.Diagnostics. It's very easy to use and to config.

Add this to the app.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="TraceTest" switchName="SourceSwitch" switchType="System.Diagnostics.SourceSwitch" >
<listeners>
<add name="FileLogListener" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" append="true" autoFlush="true" baseFilename="ImportService" location="ExecutableDirectory" logFileCreationSchedule="Daily"/>
</listeners>
</source>
</sources>
<switches>
<!--add name="SourceSwitch" value="Warning" /-->
<add name="SourceSwitch" value="Verbose"/>
</switches>
<trace autoflush="true" indentsize="4"></trace>
</system.diagnostics>
</configuration>


Then you use the trace like this:

public partial class MainForm : Form
{
private TraceSource m_traceSource = new TraceSource("TraceTest");

public MainForm()
{
InitializeComponent();
m_traceSource.TraceEvent(TraceEventType.Information, 0, "The MainForm was successfully started.");
}

No comments: