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

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

後來忽然想到了用Trace.WriteLine輸出日誌的方法,在徵得領導贊成和取得客戶的協助意願以後,按下面的步驟來實施,最終根據日誌分析找到了問題緣由:ide

  1. 在出現bug的相關上下文代碼中加入Trace.WriteLine方法,記錄下可疑的數據和狀態;
  2. 新建一個單獨的dll工程,裏面要求實現接口TraceListener,重寫WriteLine(或者Write)方法;
  3. 將生成的dll拷貝到系統啓動目錄下(與啓動exe文件平級);
  4. 修改系統配置文件(app.config),將輸出節點配置爲剛纔dll中的TraceListener實現類;
  5. 從新制做安裝包分發給客戶(或者讓程序自動更新);
  6. 讓客戶從新運行新版本程序,並重現一次bug;
  7. 讓客戶把指定位置下的日誌文件發送過來進行分析。

 

配置文件相關節點以下:測試

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

 

輸出日誌的實現類代碼以下:ui

    /// <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;
                }
            }
        }
    }

 

(完)spa

相關文章
相關標籤/搜索