問題常發生在無除錯工具的使用者機器上。.NET 提供 System.Diagnostics.Debug、Trace、EventLog 等類別,可在執行時或編譯時配置,輸出至檔案或除錯終端,並支援分級輸出。
Debug:受 DEBUG 前置處理器符號控制,通常僅偵錯版本啟用。Trace:受 TRACE 控制,VS.NET 專案預設偵錯與發行版本皆定義,適合正式環境診斷。XML 組態檔(如 MyApp.exe.config)位於應用程式目錄,根節點為 <configuration>。可定義追蹤開關與接聽項。
bool _printDiagnostics = true;
Trace.WriteLineIf(_printDiagnostics, "Printing Diagnostics Today", "MySubSystem");
開關等級:Off(0)、Error(1)、Warning(2)、Info(3)、Verbose(4)。組態檔設定:
<system.diagnostics>
<switches>
<add name="MyAssembly" value="3" />
</switches>
</system.diagnostics>
預設 DefaultTraceListener 輸出至除錯器。正式環境可加入 TextWriterTraceListener 寫入檔案:
<system.diagnostics>
<trace autoflush="true" indentsize="0">
<listeners>
<add name="MyListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="MyListener.log" />
</listeners>
</trace>
</system.diagnostics>