#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