#region 創建錯誤日誌
/// <summary>
/// 創建錯誤日誌
/// </summary>
public void createLog(Exception e)
{
//創建堆棧跟蹤器
StackTrace ss = new StackTrace(true);
//異常字符串
string systemModule = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine;
//拼接異常信息
systemModule += "異常SQL語句:" + SQLSTRING + Environment.NewLine;
//所有堆棧幀的副本
StackFrame[] sfs = ss.GetFrames();
//循環堆棧幀的副本
for (int i = 1; i < sfs.Length; i++)
{
//錯誤方法名(index:0爲本身的方法;1爲調用方法;2爲其上上層,依次類推)
MethodBase mb = ss.GetFrame(i).GetMethod();
//錯誤行號
string num = ss.GetFrame(i).GetFileLineNumber().ToString();
//拼接異常信息
systemModule += "模塊名:" + mb.Module.ToString() + Environment.NewLine;
systemModule += "命名空間名:" + mb.DeclaringType.Namespace + Environment.NewLine;
systemModule += "類名:" + mb.DeclaringType.Name + Environment.NewLine;
systemModule += "方法名:" + mb.Name + Environment.NewLine;
systemModule += "錯誤行號:" + num + Environment.NewLine;
systemModule += "異常原因:" + e.Message + Environment.NewLine;
}
//拼接異常信息
systemModule += Environment.NewLine + Environment.NewLine;
//日誌文件夾路徑
String directory = System.AppDomain.CurrentDomain.BaseDirectory;
String logPath = directory + "log";
//判斷日誌文件夾是否存在
if (!Directory.Exists(logPath))
{
//不存在創建
Directory.CreateDirectory(logPath);
}
//日誌文件(每天創建不同的日誌文件)
String logFilePath = logPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
//判斷日誌文件是否存在
if (!File.Exists(logFilePath))
{
//不存在創建日誌文件
FileStream createFS = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
createFS.Close();
}
//創建FileStream(在日誌文件後面追加寫入新日誌)
FileStream fs = new FileStream(logFilePath, FileMode.Append);
// 創建寫入流
StreamWriter sw = new StreamWriter(fs);
// 寫入異常信息
sw.WriteLine(systemModule);
//關閉文件
sw.Close();
}
#endregion