程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 利用Trace.WriteLine定位難以重現的問題,trace.writeline

利用Trace.WriteLine定位難以重現的問題,trace.writeline

編輯:C#入門知識

利用Trace.WriteLine定位難以重現的問題,trace.writeline


最近的一個項目中,在客戶測試環境(UAT)發現了一個bug,卻反復嘗試都無法在開發環境和QA環境來重現。界面上也沒有出現任何異常和錯誤,只是某個數據的顯示錯誤,其他數據都正常。仔細分析和調試了出錯位置的上下文代碼,沒有任何異常和疑點。由於是C/S結構(WPF),而技術人員也無法到達客戶現場進行協助,所以半天都沒有任何進展。

後來突然想到了用Trace.WriteLine輸出日志的方法,在征得領導同意和取得客戶的協助意願之後,按下面的步驟來實施,最終根據日志分析找到了問題原因:

 

配置文件相關節點如下:

<system.diagnostics>
    <trace>
      <listeners>
        <add name="SimpleLogTraceListener" type="TraceListenerApp.SimpleTraceListener, TraceListenerApp"/>
      </listeners>
    </trace>
  </system.diagnostics>

 

輸出日志的實現類代碼如下:

    /// <summary>
    /// A simple implementation for TraceListener to log the output to text file
    /// </summary>
    public class SimpleTraceListener : TraceListener
    {
        //default trace log file path
        string filepath = @"c:\temp\tracelog.txt";
        /// <summary>
        /// override the output from Trace.Write()
        /// </summary>
        /// <param name="message"></param>
        public override void Write(string message)
        {
            CheckLogFile();
            //format the message with datetime
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            sb.Append(DateTime.Now.ToString());
            sb.Append("]\t");
            sb.Append(message);
            using (StreamWriter sw = new StreamWriter(filepath, true))
            {
                sw.Write(sb.ToString());
                sw.Flush();
            }
        }

        /// <summary>
        /// override the output from Trace.WriteLine()
        /// </summary>
        /// <param name="message"></param>
        public override void WriteLine(string message)
        {
            CheckLogFile();
            //format the message with datetime
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            sb.Append(DateTime.Now.ToString());
            sb.Append("]\t");
            sb.Append(message);
            using (StreamWriter sw = new StreamWriter(filepath, true))
            {
                sw.WriteLine(sb.ToString());
                sw.Flush();
            }
        }

        //make sure the logfile is existing, if not, create a new one.
        void CheckLogFile()
        {
            if (!File.Exists(filepath))
            {
                try
                {
                    FileStream fs = File.Create(filepath);
                    fs.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }

 

(完)

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved