You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
3.0 KiB
C#
83 lines
3.0 KiB
C#
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("<LogDateTime>" + DateTime.Now.ToString() + "</LogDateTime>\n");
|
|
sb.Append(Environment.NewLine);
|
|
sb.Append("<Message>" + System.Net.WebUtility.HtmlEncode(e.Message) + "</Message>\n");
|
|
sb.Append(Environment.NewLine);
|
|
if (e.Source != null)
|
|
{
|
|
sb.Append("<Source>" + e.Source + "</Source>\n");
|
|
sb.Append(Environment.NewLine);
|
|
}
|
|
if (e.StackTrace != null)
|
|
{
|
|
sb.Append("<StackTrace>" + e.StackTrace + "</StackTrace>\n");
|
|
sb.Append(Environment.NewLine);
|
|
}
|
|
if (e.InnerException != null)
|
|
{
|
|
sb.Append("<InnerException>" + System.Net.WebUtility.HtmlEncode(e.InnerException.ToString()) + "</InnerException>\n");
|
|
sb.Append(Environment.NewLine);
|
|
}
|
|
sb.Append("<TargetSite>" + e.TargetSite + "</TargetSite>\n");
|
|
sb.Append(Environment.NewLine);
|
|
sb.Append("</" + ExceptionName + ">\n");
|
|
sb.Append(Environment.NewLine);
|
|
sb.Append("---------------------Footer-----------------");
|
|
sb.Append(Environment.NewLine);
|
|
|
|
return sb.ToString();
|
|
}
|
|
}
|
|
}
|