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

 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 对象时,在最后一定要记得手动关闭, 否则会造成意想不到的错误,特别是内存泄露。

异常记录的效果如下:

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
猜你喜欢
  • 2021-08-25
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
  • 2021-07-26
  • 2021-09-27
  • 2021-11-20
相关资源
相似解决方案