Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
Trace Class
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
Trace Class

Updated: August 2008

Provides a set of methods and properties that help you trace the execution of your code. This class cannot be inherited.

Namespace:  System.Diagnostics
Assembly:  System (in System.dll)
Visual Basic (Declaration)
Public NotInheritable Class Trace
Visual Basic (Usage)
Dim instance As Trace
C#
public sealed class Trace
Visual C++
public ref class Trace sealed
JScript
public final class Trace

You can use the properties and methods in the Trace class to instrument release builds. Instrumentation allows you to monitor the health of your application running in real-life settings. Tracing helps you isolate problems and fix them without disturbing a running system.

This class provides methods to display an Assert dialog box, and to emit an assertion that will always Fail. This class provides write methods in the following variations: Write, WriteLine, WriteIf, and WriteLineIf.

The BooleanSwitch and TraceSwitch classes provide means to dynamically control the tracing output. You can modify the values of these switches without recompiling your application. For information on using the configuration file to set a switch, see the Switch class and the How to: Configure Trace Switches topic.

You can customize the tracing output's target by adding TraceListener instances to or removing instances from the Listeners collection. The Listeners collection is shared by both the Debug and the Trace classes; adding a trace listener to either class adds the listener to both. By default, trace output is emitted using the DefaultTraceListener class.

NoteNote:

Adding a trace listener to the Listeners collection can cause an exception to be thrown while tracing, if a resource used by the trace listener is not available. The conditions and the exception thrown depend on the trace listener and cannot be enumerated in this topic. It may be useful to place calls to the Trace methods in try/catch blocks to detect and handle any exceptions from trace listeners.

The Trace class provides properties to get or set the level of Indent, the IndentSize, and whether to AutoFlush after each write.

To set the AutoFlush and IndentSize for Trace, you can edit the configuration file that corresponds to the name of your application. The configuration file should be formatted like the following example:

<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="3" />
  </system.diagnostics>
</configuration>

The ConditionalAttribute attribute is applied to the methods of Trace. Compilers that support ConditionalAttribute ignore calls to these methods unless "TRACE" is defined as a conditional compilation symbol. Refer to a compiler's documentation to determine whether ConditionalAttribute is supported and the syntax for defining a conditional compilation symbol.

To define the "TRACE" conditional compilation symbol in C# and J#, add the /d:TRACE option to the compiler command line when you compile your code or add #define TRACE to the top of your file. In Visual Basic, add the /d:TRACE=True option to the compiler command line or add #Const TRACE=True to the file.

ConditionalAttribute is not supported by the C++ compiler. To provide equivalent functionality, you must enclose calls to the methods of Trace in an #if defined(TRACE) ... #endif block, and add the /DTRACE option to the compiler command line or add #define TRACE to the file.

In Visual Studio 2005 projects, by default, the "DEBUG" conditional compilation symbol is defined for debug builds, and the "TRACE" symbol is defined for both debug and release builds. For information on how to disable this behavior, see the Visual Studio 2005 documentation.

Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE Platform Note: The .NET Compact Framework does not support tracing features that use a configuration file.

The following example uses Trace to indicate the beginning and the end of a program's execution. The example also uses Indent and Unindent to distinguish the tracing output.

Visual Basic
' Specify /d:TRACE=True when compiling.

Imports System
Imports System.Diagnostics

Class Test

    Shared Sub Main()

        Trace.Listeners.Add(New TextWriterTraceListener(Console.Out))
        Trace.AutoFlush = True
        Trace.Indent()
        Trace.WriteLine("Entering Main")
        Console.WriteLine("Hello World.")
        Trace.WriteLine("Exiting Main")
        Trace.Unindent()

    End Sub 'Main

End Class
C#
// Specify /d:TRACE when compiling.

using System;
using System.Diagnostics;

class Test
{
    static void Main()
    {
       Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
       Trace.AutoFlush = true;
       Trace.Indent();
       Trace.WriteLine("Entering Main");
       Console.WriteLine("Hello World.");
       Trace.WriteLine("Exiting Main"); 
       Trace.Unindent();
    }
}
Visual C++
// Specify /DTRACE when compiling.

#using <System.dll>
using namespace System;
using namespace System::Diagnostics;

int main()
{
   #if defined(TRACE)
   Trace::Listeners->Add( gcnew TextWriterTraceListener( Console::Out ) );
   Trace::AutoFlush = true;
   Trace::Indent();
   Trace::WriteLine( "Entering Main" );
   #endif
   Console::WriteLine( "Hello World." );
   #if defined(TRACE)
   Trace::WriteLine( "Exiting Main" );
   Trace::Unindent();
   #endif
   return 0;
}
System..::.Object
  System.Diagnostics..::.Trace

This type is thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Date

History

Reason

August 2008

Added note about exceptions thrown by listeners.

Customer feedback.

September 2008

Added information about the Listeners collection being shared with Debug.

Customer feedback.

Community Content   What is Community Content?
Add new content RSS  Annotations
Full trust      Rod A. Smith ... Thomas Lee   |   Edit   |   Show History

Most methods of System.Diagnostics.Trace demand unrestricted System.Security.Permissions.FileIOPermission . This can be verified by running "permcalc -Show -Out C:\Temp\System.dll.PermCalc.xml C:\Windows\Microsoft\Microsoft.NET\Framework\v2.0.50727\System.dll".

In terms of trust levels, that typically requires full trust. It would be great if those permissions demands could be relaxed, but in the meantime, when building for deployment to a partial trust environment, disable the TRACE flag.

Full trust      LukeSkywalker ... Thomas Lee   |   Edit   |   Show History

Carrying on from what Rod wrote, during a pre-shipping CAS task, I noticed that UnmanagedCode was required throughout my solution. I eventually found that it was stemming from tracing that was added to a reusable library I wrote years ago.

Consequently I am now ripping out all my tracing code, which I remember writing in my early .NET days after being advised to instrument things properly.

When searching for [ "for operating with unmanaged code" site:microsoft.com ] in Bing you get a list of Framework paraphernalia with severe security requirements such as Marshal and various window handle methods. That Trace is within this list of obviously lower-level classes and methods is rather unexpected. And like Rod above, I wonder if MS could redesign it or use Assert to insulate the caller from these requirements.

Processing
© 2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker