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


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

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

异常记录的效果如下:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM