Trace. WriteLine is used to locate the problem that is difficult to reproduce.
In a recent project, a bug was found in the customer testing environment (UAT), but repeated attempts failed to reproduce it in the development environment and QA environment. There are no exceptions or errors on the interface, but the display of a certain data is incorrect, and other data is normal. The context code of the error location is carefully analyzed and debugged without any exceptions or doubts. Since it is a C/S structure (WPF), and the technical staff cannot arrive at the customer's site for assistance, there is no progress for half a day.
Later, I suddenly thought of how to use Trace. WriteLine to output logs. After obtaining the consent of the lead and the customer's willingness to help,Perform the following steps and find the cause of the problem based on the log analysis:
The configuration file nodes are as follows:
<system.diagnostics> <trace> <listeners> <add name="SimpleLogTraceListener" type="TraceListenerApp.SimpleTraceListener, TraceListenerApp"/> </listeners> </trace> </system.diagnostics>
The output log implementation class code is as follows:
/// <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; } } } }
(End)