异常日志记录

来源:互联网 发布:mac配套手绘板 编辑:程序博客网 时间:2024/06/07 21:23

在程序运行时,出现异常的时候,常常需要氢异常信息记录下来,以便查看分析异常,准确定位 ,以下是自己写的 封装好公用 异常方法

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


0 0
原创粉丝点击