using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace AutoUpdater { public class ExceptionUtils { private static ExceptionUtils current = null; private static object lockObject = new object(); public static ExceptionUtils Current { get { if (current == null) { System.Threading.Interlocked.CompareExchange(ref current,new ExceptionUtils(), null); } return current; } } public void Handle(Exception e) { string logFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"logs"); if (!System.IO.Directory.Exists(logFile)) { System.IO.Directory.CreateDirectory(logFile); } string ExceptionName = e.GetType().Name; logFile = logFile + "\\" + ExceptionName; string filePath = logFile + DateTime.Now.ToString("yyyyMMdd") + ".log"; using (StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.Default)) { //确保线程安全 TextWriter tw = TextWriter.Synchronized(sw); tw.Write(GetExceptionInfo(e)); tw.Close(); } } public static string GetExceptionInfo(Exception e) { string ExceptionName = e.GetType().Name; StringBuilder sb = new StringBuilder(); sb.Append("---------------------Header-----------------"); sb.Append(Environment.NewLine); sb.Append("<" + ExceptionName + ">\n"); sb.Append(Environment.NewLine); sb.Append("" + DateTime.Now.ToString() + "\n"); sb.Append(Environment.NewLine); sb.Append("" + System.Net.WebUtility.HtmlEncode(e.Message) + "\n"); sb.Append(Environment.NewLine); if (e.Source != null) { sb.Append("" + e.Source + "\n"); sb.Append(Environment.NewLine); } if (e.StackTrace != null) { sb.Append("" + e.StackTrace + "\n"); sb.Append(Environment.NewLine); } if (e.InnerException != null) { sb.Append("" + System.Net.WebUtility.HtmlEncode(e.InnerException.ToString()) + "\n"); sb.Append(Environment.NewLine); } sb.Append("" + e.TargetSite + "\n"); sb.Append(Environment.NewLine); sb.Append("\n"); sb.Append(Environment.NewLine); sb.Append("---------------------Footer-----------------"); sb.Append(Environment.NewLine); return sb.ToString(); } } }