利用Trace.WriteLine定位难以重现的问题

最近的一个项目中,在客户测试环境(UAT)发现了一个bug,却反复尝试都无法在开发环境和QA环境来重现。界面上也没有出现任何异常和错误,只是某个数据的显示错误,其他数据都正常。仔细分析和调试了出错位置的上下文代码,没有任何异常和疑点。由于是C/S结构(WPF),而技术人员也无法到达客户现场进行协助,所以半天都没有任何进展。

后来突然想到了用Trace.WriteLine输出日志的方法,在征得领导同意和取得客户的协助意愿之后,按下面的步骤来实施,最终根据日志分析找到了问题原因:

  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>

 

输出日志的实现类代码如下:

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

 

(完)

 

posted @ 2015-05-12 00:41  无待  阅读(3714)  评论(2编辑  收藏  举报