您的位置:首页 > 编程语言 > C#

在 C# 控制台中记录异常日志并输出

2015-05-19 16:20 337 查看
最近做了一个小程序,要求在控制台中记录程序运行的异常并输出到指定的文件夹中,以下是我的具体的程序代码:

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();
}

}


使用这个异常日志记录方法 ,在程序可能出现异常的地方用 try ... catch 块来包装, 并在 catch 块中 调用这个异常的方法,将异常日志记录下来, 在使用 TextWrite 对象时,在最后一定要记得手动关闭, 否则会造成意想不到的错误,特别是内存泄露。

异常记录的效果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: