using System;
using System.IO;
using System.Text;
namespace POSV.Utils
{
public class ExceptionUtils
{
private static ExceptionUtils _current = null;
public static ExceptionUtils Current
{
get
{
if (_current == null)
{
System.Threading.Interlocked.CompareExchange(ref _current , new ExceptionUtils() , null);
}
return _current;
}
}
public void Handle(Exception e)
{
try
{
string logFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"logs\errors");
if (!Directory.Exists(logFile))
{
Directory.CreateDirectory(logFile);
}
string exceptionName = e.GetType().Name;
string filePath = logFile + @"\" + DateTime.Now.ToString("yyyyMMdd") + ".log";
if (!File.Exists(logFile))
{
File.Create(filePath);
}
using (StreamWriter sw = new StreamWriter(filePath, true, Encoding.Default))
{
//确保线程安全
TextWriter tw = TextWriter.Synchronized(sw);
tw.Write(GetExceptionInfo(e));
tw.Close();
}
}
catch
{
}
}
public static string GetExceptionInfo(Exception e)
{
string exceptionName = e.GetType().Name;
StringBuilder sb = new StringBuilder();
sb.Append(Environment.NewLine);
sb.Append("---------------------Header-----------------");
sb.Append(Environment.NewLine);
sb.Append("<" + exceptionName + ">\n");
sb.Append(Environment.NewLine);
sb.Append("" + DateTime.Now + "\n");
sb.Append(Environment.NewLine);
sb.Append("" + System.Net.WebUtility.HtmlEncode(e.Message) + "\n");
sb.Append(Environment.NewLine);
if (e.Source != null)
{
sb.Append("\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("" + exceptionName + ">\n");
sb.Append(Environment.NewLine);
sb.Append("---------------------Footer-----------------");
sb.Append(Environment.NewLine);
return sb.ToString();
}
}
}