using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Ella.ToolKit
{
/// <summary>
/// 日志操作
/// <para/>Author : AnDequan
/// <para/>Date : 2010-12-23
/// </summary>
public sealed class LogHelper : Singleton<LogHelper>
{
/// <summary>
/// 记录异常日志
/// <para/>Author : AnDequan
/// <para/>Date : 2010-12-2
/// </summary>
/// <param name="ex">异常</param>
public void Add(Exception ex)
{
DateTime dtLog = DateTime.Now;
string sPath = @"D:/LogInfo/" + dtLog.Year + "//" + dtLog.Month;
ErrorRecord(ex, sPath);
}
/// <summary>
/// 记录异常日志
/// <para/>Author : AnDequan
/// <para/>Date : 2010-12-2
/// </summary>
/// <param name="ex">异常</param>
/// <param name="path">生成错误信息的文件路径</param>
public void Add(Exception ex, string path)
{
ErrorRecord(ex, path);
}
#region User-Defined Private Function (辅助方法)
/// <summary>
/// 生成错误字符串
/// <para/>Author : AnDequan
/// <para/>Date : 2010-12-2
/// </summary>
/// <param name="ex">错误</param>
/// <returns>错误信息</returns>
private string GetLogInfo(Exception ex)
{
StringBuilder sbLog = new StringBuilder();
sbLog.AppendLine("记录时间:" + DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString());
sbLog.AppendLine("异常实例: " + ex.InnerException.ToString());
sbLog.AppendLine("引发当前异常的方法: " + ex.TargetSite.ToString());
sbLog.AppendLine("导致错误的应用程序或对象的名称: " + ex.Source);
sbLog.AppendLine("");
return sbLog.ToString();
}
/// <summary>
/// 记录程序中的错误
/// <para/>Author : AnDequan
/// <para/>Date : 2010-11-4
/// </summary>
/// <param name="ex">异常信息</param>
/// <param name="path">生成错误信息的文件路径</param>
private void ErrorRecord(Exception ex, string path)
{
string sFileName = DateTime.Now.ToLongDateString() + ".txt";
if (!File.Exists(path + "//" + sFileName))
{
Directory.CreateDirectory(path);
using (FileStream fsError = new FileStream(path + "//" + sFileName, FileMode.Create))
{
using (StreamWriter swError = new StreamWriter(fsError))
{
swError.WriteLine(GetLogInfo(ex));
}
}
}
else
{
using (FileStream fsError = new FileStream(path + "//" + sFileName, FileMode.Append))
{
using (StreamWriter swError = new StreamWriter(fsError))
{
swError.WriteLine(GetLogInfo(ex));
}
}
}
}
#endregion
}
}