Effective C#學習筆記:適當使用.NET運行時診斷

來源:互聯網
上載者:User

System.Diagnostics下面有三個類可以協助我們診斷應用程式:

  1. Debug
  2. Trace
  3. EventLog

建立一個VS工程時,VS會為我們定義Trace和Debug這兩個符號,它們的區別是Trace在release版本時也有效,而Debug只在Debug版本中有效。EventLog可以將日誌記錄到Windows的系統日誌中.

Trace和Debug這兩個類可以說用著相同的功能,只是Trace更強大些,預設情況下,它們的輸出是調試器的Console。

樣本(API的基本使用):

class Program
    {
        static TraceSwitch GlobalSwitch = new TraceSwitch("Test", "Test TraceSwitch");
        static void Main(string[] args)
        {
           
            Trace.WriteLine("AutoFlush = " +  Trace.AutoFlush.ToString());
            Trace.WriteLine("My Trace Message");
            Trace.WriteLine("My Trace Message", "Log1");
            if (!Trace.AutoFlush)
            {
                Trace.Flush();
            }

            Trace.WriteLineIf(GlobalSwitch.Level >= TraceLevel.Warning, "If error or warning");

            //Debug.WriteLine("AutoFlush=" + Debug.AutoFlush.ToString());
            //Debug.WriteLine("My Debug Message");
            //Debug.WriteLine("My Debug Message", "Log1");   
            Debug.WriteLineIf(DateTime.Now.Year > 2007, " today > 2007");
            if (!Debug.AutoFlush)
            {
                Debug.Flush();
            }                                       
         
            Console.ReadLine();
        }
    }

 

Trace還和TraceSwitch可以搭配使用,來達到按層級配置輸出的目的。還可以使用自訂的Listener

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <trace autoflush="true" indentsize="0">
            <listeners>
                <add name="MyListener"
                     type="System.Diagnostics.TextWriterTraceListener"
                     initializeData="MyListener.log"/>
                <add name="MyListener2"
                     type="DiagnosticsApp.MyTraceListener, DiagnosticsApp"
                    />
            </listeners>
        </trace>
        <switches>
            <add name="Test" value="4"/>              
        </switches>
    </system.diagnostics>
</configuration>

  Trace.WriteLineIf(GlobalSwitch.Level >= TraceLevel.Warning, "If error or warning...");

public class MyTraceListener : System.Diagnostics.TraceListener
    {
        public override void Write(string message)
        {
            Console.Out.Write(message);
        }

        public override void WriteLine(string message)
        {
            Console.Out.WriteLine(message);
        }
    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.