在程序运行时,出现异常的时候,常常需要氢异常信息记录下来,以便查看分析异常,准确定位 ,以下是自己写的 封装好公用 异常方法
public static void ErrorLog(Exception ex)
{
string FilePath = "/ErrorLog.txt";
StringBuilder msg = new StringBuilder ();
msg.Append("*************************************** \n");
msg.AppendFormat(" 异常发生时间: {0} \n",DateTime.Now);
msg.AppendFormat(" 异常类型: {0} \n",ex.HResult);
msg.AppendFormat(" 导致当前异常的 Exception 实例: {0} \n",ex.InnerException);
msg.AppendFormat(" 导致异常的应用程序或对象的名称: {0} \n",ex.Source);
msg.AppendFormat(" 引发异常的方法: {0} \n",ex.TargetSite);
msg.AppendFormat(" 异常堆栈信息: {0} \n",ex.StackTrace);
msg.AppendFormat(" 异常消息: {0} \n",ex.Message);
msg.Append("***************************************");
try
{
if (File.Exists(FilePath))
{
using (StreamWriter tw = File.AppendText(FilePath))
{
tw.WriteLine(msg.ToString());
}
}
else
{
TextWriter tw = new StreamWriter(FilePath);
tw.WriteLine(msg.ToString());
tw.Flush();
tw.Close();
tw = null;
}
}
catch (Exception)
{
Console.ReadKey();
}
}
异常日志记录方法

本文介绍了一种在程序中记录异常信息的日志方法。通过自定义的ErrorLog方法,可以详细记录异常的时间、类型、来源等关键信息,并将这些信息保存到指定文件中,便于后续的异常排查和定位。

被折叠的 条评论
为什么被折叠?



