最近的一个项目中,在客户测试环境(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; } } } }
(完)