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.

91 lines
3.1 KiB
C#

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("<LogDateTime>" + DateTime.Now + "</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();
}
}
}