错误日记记录下来方便查看错误,虽然window有自己的日志文件,但每次都要查好久才能找到错误点,记得有一次,服务器上的winform程序老是自动关掉,开始查不出原因,后来才发现是socket通信的错误,错误具体现在也忘了,后来写了个错误日志记录下,很轻易就找到了错误。
/// <summary> /// 错误日志 /// </summary> /// <param name="LogFileRelativePath">路径</param> /// <returns></returns> private static void WriteLogToFile(string LogFileRelativePath) { IsWriteLogToFileNow = true; FileStream fs; string LogFileAbsolutePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LogFileRelativePath); if (!File.Exists(LogFileAbsolutePath)) { string LogFolderAbsolutePath = System.IO.Path.GetDirectoryName(LogFileAbsolutePath); if (!Directory.Exists(LogFolderAbsolutePath)) { Directory.CreateDirectory(LogFolderAbsolutePath); } fs = File.Create(LogFileAbsolutePath); } else { fs = new FileStream(LogFileAbsolutePath, FileMode.Append, FileAccess.Write); } LogInfo _LogInfo; StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("gb2312")); while (LogInfoQueue.Count > 0) { _LogInfo = LogInfoQueue.Dequeue(); if (_LogInfo != null) { sw.WriteLine(_LogInfo.DateTime.ToString()); foreach (String LogString in _LogInfo.InfoList) { sw.WriteLine(LogString); } sw.WriteLine(); } } sw.Close(); fs.Close(); IsWriteLogToFileNow = false; }
winform中和C#中的代码都差不多的,错误日志也有不好的,就是如果哪一步出现BUG,日志可能非常大,这个要注意的