Trace

How to: Add Trace Statements to Application Code

The methods used most often for tracing are the methods for writing output to listeners: Write, WriteIf, WriteLine, WriteLineIf, Assert, and Fail. These methods can be divided into two categories: Write, WriteLine, and Fail all emit output unconditionally, whereas WriteIf, WriteLineIf, and Assert test a Boolean condition, and write or do not write based on the value of the condition. WriteIf and WriteLineIf emit output of the condition is true, and Assert emits output if the condition is false.

When designing your tracing and debugging strategy, you should think about how you want the output to look. Multiple Write statements filled with unrelated information will create a log that is difficult to read. On the other hand, using WriteLine to put related statements on separate lines may make it difficult to distinguish what information belongs together. In general, use multiple Write statements when you want to combine information from multiple sources to create a single informative message, and the WriteLine statement when you want to create a single, complete message.

To write a complete line

  • Call the WriteLine or WriteLineIf method.

    A carriage return is appended to the end of the message this method returns, so that the next message returned by Write, WriteIf, WriteLine, or WriteLineIf will begin on the following line:

    C#
    VB
    bool errorFlag = false;
    System.Diagnostics.Trace.WriteLine ("Error in AppendData procedure.");
    System.Diagnostics.Trace.WriteLineIf(errorFlag, 
       "Error in AppendData procedure.");
    
    

To write a partial line

  • Call the Write or WriteIf method.

    The next message put out by a Write, WriteIf, WriteLine, or WriteLineIf will begin on the same line as the message put out by the Write or WriteIf statement:

    C#
    VB
    bool errorFlag = false;
    System.Diagnostics.Trace.WriteIf(errorFlag, 
       "Error in AppendData procedure.");
    System.Diagnostics.Debug.WriteIf(errorFlag, "Transaction abandoned.");
    Trace.Write("Invalid value for data request");
    
    

To verify that certain conditions exist either before or after you execute a method

  • Call the Assert method.

    C#
    VB
    int I = 4;
    System.Diagnostics.Trace.Assert(I == 5, "I is not equal to 5.");
    
    
    NoteNote

    You can use Assert with both tracing and debugging. This example outputs the call stack to any listener in the Listeners collection. For more information, see Assertions in Managed Code and Debug.Assert.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值