Trace 與 Debug 類

來源:互聯網
上載者:User

標籤:狀態   margin   dia   程式   測試的   zed   initial   indent   int   

一、概述

Debug 類用於開發階段,Trace 類用於開發與測試階段,大部分用於追蹤程式碼的狀態或行為。

Trace.WriteLine("Trace Information");
Trace.WriteLine("一般資訊");
Trace.TraceInformation("告知性資訊");
Trace.TraceWarning("警告資訊");
Trace.TraceError("錯誤資訊");

二、Assert 方法

Trace 與 Debug 類的Assert方法和單元測試的Assert方法非常類似,它會進行條件檢查,如果條件為false時,除了會輸出至輸出視窗外,還會“快顯視窗”已明確顯示資訊(內部調用Fail方法)

static void Main(string[] args)
{
int UnitQty = 1000;
double UnitCost = 99;
DebugStatus(UnitQty, UnitCost);
Console.ReadLine();
}

static void DebugStatus(int UnitQty, double UnitCost)
{
Trace.WriteLine("一般資訊");
Debug.WriteLine("總成本:" + (UnitQty * UnitCost));

Debug.WriteLineIf(UnitQty > 100, "庫存>100本");
Debug.WriteLineIf(UnitQty < 100, "庫存<100");
Trace.TraceError("錯誤資訊");
Debug.Assert(!(UnitCost > 1000), "成本>1000 太貴了!");
Debug.Assert(!(UnitCost < 100), "成本<100 不合理!");
}

 三、Listeners 集合

  Trace 與 Debug 類預設會輸出資訊至Visual Studio 的“輸出表單”。也可以設定多個監聽器(Listeners)來輸出至各種媒體,文字檔,CSV,XML,事件檢視器等等,預設使用DefaultTraceListener類。

  1.TextWriterTraceListener 可通過Web.Config和程式碼兩種方式配置

    Web.config的配置方式:

<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<remove name="Default"/>
<add name="TraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="E:\TraceMessage.log"/>
</listeners>
</trace>
</system.diagnostics>

如果 autoflush="false",必須在程式中調用Flush方法輸出至文字檔。

    程式碼的配置方式:

TextWriterTraceListener textListener = new TextWriterTraceListener(System.IO.File.CreateText("Debug.txt"));
Debug.Listeners.Add(textListener);

2.EventLogTraceListener

Web.config的配置方式:

<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<remove name="Default"/>
<add name="TraceListener" type="System.Diagnostics.EventLogTraceListener" initializeData="Application"/>
</listeners>
</trace>
</system.diagnostics>

程式碼的配置方式:

EventLogTraceListener eventLog = new EventLogTraceListener("Application");
Trace.Listeners.Add(eventLog);
Trace.TraceInformation("Send trace info test.");

    

Trace 與 Debug 類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.