DefaultTraceListener
Class
Definition
Provides the default output methods and behavior for tracing.
public class DefaultTraceListener : System.Diagnostics.TraceListener
- Inheritance
Inherited Members
System.Diagnostics.TraceListener
System.MarshalByRefObject
System.Object
Examples
The following code example calculates binomial coefficients, which are values used in probability and statistics. This example uses a DefaultTraceListener to trace results and log errors. It creates a new DefaultTraceListener, adds it to the Trace.Listeners collection, and sets the LogFileName property to the log file specified in the command-line arguments.
If an error is detected while processing the input parameter, or if the CalcBinomial function throws an exception, the Fail method logs and displays an error message. If the AssertUiEnabled property is false, the error message is also written to the console. When the result is calculated successfully, the Write(String) and WriteLine(String) methods write the results to the log file.
The Fail, Write, and WriteLine methods cause trace information to be written only to the DefaultTraceListener. To write trace information to all listeners in the Trace.Listeners collection, use the Fail, Write, and WriteLine methods of the Trace class.
using System;
using System.Diagnostics;
using Microsoft.VisualBasic;
class Binomial
{
// args(0) is the number of possibilities for binomial coefficients.
// args(1) is the file specification for the trace log file.
public static void Main(string[] args)
{
decimal possibilities;
decimal iter;
// Remove the original default trace listener.
Trace.Listeners.RemoveAt(0);
// Create and add a new default trace listener.
DefaultTraceListener defaultListener;
defaultListener = new DefaultTraceListener();
Trace.Listeners.Add(defaultListener);
// Assign the log file specification from the command line, if entered.
if (args.Length>=2)
{
defaultListener.LogFileName = args[1];
}
// Validate the number of possibilities argument.
if (args.Length>=1)
// Verify that the argument is a number within the correct range.
{
try
{
const decimal MAX_POSSIBILITIES = 99;
possibilities = Decimal.Parse(args[0]);
if (possibilities<0||possibilities>MAX_POSSIBILITIES)
{
throw new Exception(String.Format("The number of possibilities must " +
"be in the range 0..{0}.", MAX_POSSIBILITIES));
}
}
catch(Exception ex)
{
string failMessage = String.Format("\"{0}\" " +
"is not a valid number of possibilities.", args[0]);
defaultListener.Fail(failMessage, ex.Message);
if (!defaultListener.AssertUiEnabled)
{
Console.WriteLine(failMessage+ "\n" +ex.Message);
}
return;
}
}
else
{
// Report that the required argument is not present.
const string ENTER_PARAM = "Enter the number of " +
"possibilities as a command line argument.";
defaultListener.Fail(ENTER_PARAM);
if (!defaultListener.AssertUiEnabled)
{
Console.WriteLine(ENTER_PARAM);
}
return;
}
for(iter=0; iter<=possibilities; iter++)
{
decimal result;
string binomial;
// Compute the next binomial coefficient and handle all exceptions.
try
{
result = CalcBinomial(possibilities, iter);
}
catch(Exception ex)
{
string failMessage = String.Format("An exception was raised when " +
"calculating Binomial( {0}, {1} ).", possibilities, iter);
defaultListener.Fail(failMessage, ex.Message);
if (!defaultListener.AssertUiEnabled)
{
Console.WriteLine(failMessage+ "\n" +ex.Message);
}
return;
}
// Format the trace and console output.
binomial = String.Format("Binomial( {0}, {1} ) = ", possibilities, iter);
defaultListener.Write(binomial);
defaultListener.WriteLine(result.ToString());
Console.WriteLine("{0} {1}", binomial, result);
}
}
public static decimal CalcBinomial(decimal possibilities, decimal outcomes)
{
// Calculate a binomial coefficient, and minimize the chance of overflow.
decimal result = 1;
decimal iter;
for(iter=1; iter<=possibilities-outcomes; iter++)
{
result *= outcomes+iter;
result /= iter;
}
return result;
}
}
Imports System
Imports System.Diagnostics
Imports Microsoft.VisualBasic
Module Binomial
' args(0) is the number of possibilities for binomial coefficients.
' args(1) is the file specification for the trace log file.
Sub Main(ByVal args() As String)
Dim possibilities As Decimal
Dim iter As Decimal
' Remove the original default trace listener.
Trace.Listeners.RemoveAt(0)
' Create and add a new default trace listener.
Dim defaultListener As DefaultTraceListener
defaultListener = New DefaultTraceListener
Trace.Listeners.Add(defaultListener)
' Assign the log file specification from the command line, if entered.
If args.Length >= 2 Then
defaultListener.LogFileName = args(1)
End If
' Validate the number of possibilities argument.
If args.Length >= 1 Then
' Verify that the argument is a number within the correct range.
Try
Const MAX_POSSIBILITIES As Decimal = 99
possibilities = Decimal.Parse(args(0))
If possibilities < 0 Or possibilities > MAX_POSSIBILITIES Then
Throw New Exception( _
String.Format("The number of possibilities must " & _
"be in the range 0..{0}.", MAX_POSSIBILITIES))
End If
Catch ex As Exception
Dim failMessage As String = String.Format("""{0}"" " & _
"is not a valid number of possibilities.", args(0))
defaultListener.Fail(failMessage, ex.Message)
If Not defaultListener.AssertUiEnabled Then
Console.WriteLine(failMessage & vbCrLf & ex.Message)
End If
Return
End Try
Else
' Report that the required argument is not present.
Const ENTER_PARAM As String = "Enter the number of " & _
"possibilities as a command line argument."
defaultListener.Fail(ENTER_PARAM)
If Not defaultListener.AssertUiEnabled Then
Console.WriteLine(ENTER_PARAM)
End If
Return
End If
For iter = 0 To possibilities
Dim result As Decimal
Dim binomial As String
' Compute the next binomial coefficient and handle all exceptions.
Try
result = CalcBinomial(possibilities, iter)
Catch ex As Exception
Dim failMessage As String = String.Format( _
"An exception was raised when " & _
"calculating Binomial( {0}, {1} ).", _
possibilities, iter)
defaultListener.Fail(failmessage, ex.Message)
If Not defaultListener.AssertUiEnabled Then
Console.WriteLine(failMessage & vbCrLf & ex.Message)
End If
Return
End Try
' Format the trace and console output.
binomial = String.Format("Binomial( {0}, {1} ) = ", _
possibilities, iter)
defaultListener.Write(binomial)
defaultListener.WriteLine(result.ToString)
Console.WriteLine("{0} {1}", binomial, result)
Next
End Sub
Function CalcBinomial(ByVal possibilities As Decimal, _
ByVal outcomes As Decimal) As Decimal
' Calculate a binomial coefficient, and minimize the chance of overflow.
Dim result As Decimal = 1
Dim iter As Decimal
For iter = 1 To possibilities - outcomes
result *= outcomes + iter
result /= iter
Next
Return result
End Function
End Module
Remarks
An instance of this class is automatically added to the Debug.Listeners and Trace.Listeners collections. Explicitly adding a second DefaultTraceListener causes duplicate messages in the debugger output window and duplicate message boxes for asserts.
By default, the Write and WriteLine methods emit the message to the Win32 OutputDebugString function and to the Debugger.Log method. For information about the OutputDebugString function, see the Platform SDK or MSDN.
The Fail method, by default, displays a message box when the application is running in a user interface mode; it also emits the message using WriteLine.
Note
The display of the message box for Assert and Fail method calls depends on the presence of the DefaultTraceListener. If the DefaultTraceListener is not in the Listeners collection, the message box is not displayed. The DefaultTraceListener can be removed by the <clear> element, by the <remove> element, or by calling the Clear method on the Listeners property (System.Diagnostics.Trace.Listeners.Clear()).
You must enable tracing or debugging to use a trace listener. The following syntax is compiler specific. If you use compilers other than C# or Visual Basic, refer to the documentation for your compiler.
To enable debugging in C#, add the
/d:DEBUGflag to the compiler command line when you compile your code, or add#define DEBUGto the top of your file. In Visual Basic, add the/d:DEBUG=Trueflag to the compiler command line.To enable tracing in C#, add the
/d:TRACEflag to the compiler command line when you compile your code, or add#define TRACEto the top of your file. In Visual Basic, add the/d:TRACE=Trueflag to the compiler command line.
To add a trace listener, edit the configuration file that corresponds to the name of your application. Within this file, you can add a listener, set its type and set its parameters, remove a listener, or clear all the listeners previously set by the application. The configuration file should be formatted similar to the following example:
<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<remove name="Default" />
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\myListener.log" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
Constructors
| DefaultTraceListener() |
Initializes a new instance of the DefaultTraceListener class with "Default" as its Name property value. |
Properties
| AssertUiEnabled |
Gets or sets a value indicating whether the application is running in user-interface mode. |
| LogFileName |
Gets or sets the name of a log file to write trace or debug messages to. |
Methods
| Fail(String) |
Emits or displays a message and a stack trace for an assertion that always fails. |
| Fail(String, String) |
Emits or displays detailed messages and a stack trace for an assertion that always fails. |
| Write(String) |
Writes the output to the |
| WriteLine(String) |
Writes the output to the |
Thread Safety
This class is thread safe.