How to Use the debug and trace classes

Source: Internet
Author: User

 

This topic describes how to use DebugAnd TraceClass. Microsoft. NET Framework provides these two classes. You can use these two classes to provide information about application performance during application development or after deployment to the product. These two classes are only part of the configuration functions provided in. NET Framework.

Back to Top Requirement

The following list summarizes the recommended hardware, software, network structure, and required Service Packs:

  • Microsoft Windows 2000 or Microsoft Windows XP
  • Microsoft Visual C #. net

This article also assumes that you are familiar with program debugging.

Back to Top


The steps described in the example section for creating a debug class demonstrate how to create and useDebugClass to provide information about program execution.

You can useDebugTo help you monitor the program execution sequence, detect faults, or provide performance metrics. By default,DebugMessages generated by class are displayed in the "output" Window of Visual Studio integrated development environment (IDE.

Use this sample codeWritelineMethod to generate a message with a line terminator. When you use this method to generate a message, each message is displayed as a separate line in the "output" window.

If you useDebugClassAssertThe "output" window displays messages only when the specified condition is calculated as false. The message is displayed in a mode dialog box. This dialog box includes the message, project name, andDebug. AssertStatement number. The dialog box also contains the following command buttons:

  • Termination:The application stops running.
  • Retry:The application enters the debugging mode.
  • Ignore:The application continues.

You must click one of these buttons before the application can continue.

You can also specifyDebugClass to the target outside the "output" window.DebugClass has a nameListeners.ListenerObject.

EachListenerObject monitoringDebugOutput and direct the output to the specified target.

ListenerEachListenerAll receiveDebugClass. Please useTextwritertracelistenerClass DefinitionListenerObject. You can useTextwritertracelistenerClass constructor specifies the target for this class.

Some possible output targets include:

  • UseSystem. Console. OutAttribute specifies the "console" window as the output target.
  • UseSystem. Io. file. createtext ("filename.txt ")Statement specifies the text file (.txt) as the output target.

CreateTextwritertracelistenerObject, you must add the objectDebug. ListenersSet to receive debugging output.

Return to the top and use the debug class to create an example.

  1. Start Visual Studio. NET.
  2. Create a New Visual C #. Net console application project named coninfo. Class1 will be created.
  3. Add the following namespace at the top of class1.
    using System.Diagnostics;

  4. To initialize a variable to include information about the product, add the following statementMainMethod:
    string sProdName = "Widget";int iUnitQty = 100;double dUnitCost = 1.03;

  5. Specify the message generated by the classWritelineThe first input parameter of the method. Press CTRL + ALT + O to make sure the "output" window is visible.
    Debug.WriteLine("Debug Information-Product Starting ");

  6. UseIndentMethod to indent the following message in the "output" window:
    Debug.Indent();

  7. To display the content of the selected variable, useWritelineMethod:
    Debug.WriteLine("The product name is " + sProdName);Debug.WriteLine("The available units on hand are" + iUnitQty.ToString());Debug.WriteLine("The per unit cost is " + dUnitCost.ToString());

  8. You can also useWritelineMethod to display the namespace and class name of an existing object. For example, the following code is displayed in the "output" window.System. xml. xmldocumentNamespace:
    System.Xml.XmlDocument oxml = new System.Xml.XmlDocument();Debug.WriteLine(oxml);

  9. To sort out the output, you can include a categoryWritelineThe second optional input parameter of the method. If you specify a category, the format of the "output" window message is "category: Message ". For example, the first line of the following code displays "field: the product name is widget" in the "output" window ":
    Debug.WriteLine("The product name is " + sProdName,"Field");Debug.WriteLine("The units on hand are" + iUnitQty,"Field");Debug.WriteLine("The per unit cost is" + dUnitCost.ToString(),"Field");Debug.WriteLine("Total Cost is  " + (iUnitQty * dUnitCost),"Calc");

  10. Only in useDebugClassWritelineifThe "output" window displays messages only when the specified condition is calculated as true. The condition to be calculated isWritelineifThe first input parameter of the method.WritelineifThe second parameter is the message displayed only when the condition of the first parameter is calculated as true.
    Debug.WriteLineIf(iUnitQty > 50, "This message WILL appear");Debug.WriteLineIf(iUnitQty < 50, "This message will NOT appear");

  11. UseDebugClassAssertSo that the "output" window displays messages only when the specified condition is calculated as false:
    Debug.Assert(dUnitCost > 1, "Message will NOT appear");Debug.Assert(dUnitCost < 1, "Message will appear since dUnitcost < 1 is false");

  12. Create a text file named output.txt (tr2) in the "console" window (tr1)TextwritertracelistenerObject, and then add each objectDebug listenersCollection:
    TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);Debug.Listeners.Add(tr1);        TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));Debug.Listeners.Add(tr2);

  13. UseUnindentMethod RemovalDebugClass is the indent generated for subsequent messages. When youIndentAndUnindentWhen the two methods are used together, the reader can divide the output into groups.
    Debug.Unindent();Debug.WriteLine("Debug Information-Product Ending");

  14. To ensure that eachListenerThe object receives all its output.DebugClass Buffer callFlushMethod:
    Debug.Flush();

Back to the top using the trace class

You can also useTraceClass to generate messages that monitor application execution.TraceAndDebugClasses share most of the same methods to generate output. These methods include:

  • Writeline
  • Writelineif
  • Indent
  • Unindent
  • Assert
  • Flush

You can useTraceAndDebugClass. In a "Debug solution configuration" project,TraceAndDebugBoth outputs are active. The project from these two classes isListenerObject generation and output. However, the "Release solution configuration" project is only fromTraceClass generation output. This release solution configuration item ignores anyDebugClass method call.

Trace.WriteLine("Trace Information-Product Starting ");Trace.Indent();Trace.WriteLine("The product name is "+sProdName);Trace.WriteLine("The product name is"+sProdName,"Field" );Trace.WriteLineIf(iUnitQty > 50, "This message WILL appear");Trace.Assert(dUnitCost > 1, "Message will NOT appear");        Trace.Unindent();Trace.WriteLine("Trace Information-Product Ending");Trace.Flush();Console.ReadLine();

Return to the top to confirm it can be used

  1. EnsureDebugIs the current solution configuration.
  2. If the Solution Explorer window is invisible, press CTRL + ALT + L to display the window.
  3. Right-click "coninfo" and then click "properties ".
  4. In the left pane of the coninfo properties page, under the configuration folder, make sure that the arrow points to debug ".
  5. In the "configuration" drop-down list box on the "configuration" folder, click "activity (Debug)" or "debug", and then click "OK ".
  6. Press CTRL + ALT + O to display the "output" window.
  7. Press F5 to run the code. When the "assertion failed" dialog box appears, click "Ignore ".
  8. In the "console" window, press Enter. In this case, the program is completed, and the "output" window should display the following output:
        Debug Information-Product Starting     The product name is Widget    The available units on hand are100    The per unit cost is 1.03    System.Xml.XmlDocument    Field: The product name is Widget    Field: The units on hand are100    Field: The per unit cost is1.03    Calc: Total Cost is  103    This message WILL appear    ---- DEBUG ASSERTION FAILED -------- Assert Short Message ----Message will appear since dUnitcost  < 1 is false---- Assert Long Message ----    at Class1.Main(String[] args)  <%Path%>\class1.cs(34)    The product name is Widget    The available units on hand are100    The per unit cost is 1.03Debug Information-Product EndingTrace Information-Product Starting     The product name is Widget    Field: The product name isWidget    This message WILL appearTrace Information-Product Ending                    

  9. The "console" window and output.txt file should display the following output:
    The product name is Widget    The available units on hand are 100    The per unit cost is 1.03Debug Information-Product EndingTrace Information-Product Starting     The product name is Widget    Field: The product name is Widget    This message WILL appearTrace Information-Product Ending

Note:: The output.txt file and the coninfo Executable File (coninfo.exe) are located in the same directory. Normally, this directory is the \ bin folder that stores the project source. The default directory is c: \ Documents ents and Settings \ User Login \ My Documents ents \ Visual Studio projects \ coninfo \ bin.

Return to the complete code list at the top

   using System;   using System.Diagnostics;   class Class1   {      [STAThread]      static void Main(string[] args)      {         string sProdName = "Widget";         int iUnitQty = 100;         double  dUnitCost = 1.03;         Debug.WriteLine("Debug Information-Product Starting ");         Debug.Indent();         Debug.WriteLine("The product name is "+sProdName);         Debug.WriteLine("The available units on hand are"+iUnitQty.ToString());         Debug.WriteLine("The per unit cost is "+ dUnitCost.ToString());         System.Xml.XmlDocument oxml = new System.Xml.XmlDocument();         Debug.WriteLine(oxml);         Debug.WriteLine("The product name is "+sProdName,"Field");         Debug.WriteLine("The units on hand are"+iUnitQty,"Field");         Debug.WriteLine("The per unit cost is"+dUnitCost.ToString(),"Field");         Debug.WriteLine("Total Cost is  "+(iUnitQty * dUnitCost),"Calc");         Debug.WriteLineIf(iUnitQty > 50, "This message WILL appear");         Debug.WriteLineIf(iUnitQty < 50, "This message will NOT appear");         Debug.Assert(dUnitCost > 1, "Message will NOT appear");         Debug.Assert(dUnitCost < 1, "Message will appear since dUnitcost  < 1 is false");         TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);         Debug.Listeners.Add(tr1);                 TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));         Debug.Listeners.Add(tr2);                   Debug.WriteLine("The product name is "+sProdName);         Debug.WriteLine("The available units on hand are"+iUnitQty);         Debug.WriteLine("The per unit cost is "+dUnitCost);         Debug.Unindent();         Debug.WriteLine("Debug Information-Product Ending");         Debug.Flush();                  Trace.WriteLine("Trace Information-Product Starting ");         Trace.Indent();         Trace.WriteLine("The product name is "+sProdName);         Trace.WriteLine("The product name is"+sProdName,"Field" );         Trace.WriteLineIf(iUnitQty > 50, "This message WILL appear");         Trace.Assert(dUnitCost > 1, "Message will NOT appear");                 Trace.Unindent();         Trace.WriteLine("Trace Information-Product Ending");         Trace.Flush();         Console.ReadLine();      }   }

Note:: To make this sample code take effect, you mustUsing system. diagnostics;Paste it as the first line of code to addSystem. diagonsticsNamespace.

Back to Top troubleshooting

  • If the solution configuration type isReleaseWill ignoreDebugClass output.
  • CreateTextwritertracelistenerClass,TextwritertracelistenerFromTraceClass andDebugClass receiving output. Whether or not you useTraceOrDebugClassAddMethodTextwritertracelistenerAddListenersClass.
  • IfListenersAdd objectTraceClass andDebugClass, whether it isDebugClass orTraceClass to generate the output.
             TextWriterTraceListener myWriter = new TextWriterTraceListener(System.Console.Out);         Debug.Listeners.Add(myWriter);                 TextWriterTraceListener myCreator = new TextWriterTraceListener(System.Console.Out);         Trace.Listeners.Add(myCreator);         

Back to Top

Reference

For more information, see the following topics in the. NET Framework class library documentation: trace class http://msdn2.microsoft.com/en-us/li...

For more information, see the following topics in the. NET Framework class library documentation:

Trace class
Http://msdn2.microsoft.com/en-us/library/system.diagnostics.trace (vs.71). aspx (http://msdn2.microsoft.com/en-us/library/system.diagnostics.trace (vs.71). aspx)

Debug class
Http://msdn2.microsoft.com/en-us/library/system.diagnostics.debug (vs.71). aspx (http://msdn2.microsoft.com/en-us/library/system.diagnostics.debug (vs.71). aspx)

For more information about tracing, see the following topics in the Microsoft gotdotnet Quick Start Tutorial:

How to use tracking?
Http://samples.gotdotnet.com/quickstart/howto/doc/Trace.aspx (http://samples.gotdotnet.com/quickstart/howto/doc/Trace.aspx) Back to Top

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.