c#简单自定义异常处理日志辅助类

 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 
  namespace LogHelper
  {
     public static class LogHelper
     {
         //拼接日志目录
         static string appLogPath = AppDomain.CurrentDomain.BaseDirectory + "log/";
         /// <summary>
         /// 写入日志
         /// </summary>
         /// <param name="ex">异常对象</param>
         public static void WriteLog(Exception ex)
         {
             //日志目录是否存在 不存在创建
             if (!Directory.Exists(appLogPath))
            {
                Directory.CreateDirectory(appLogPath);
            }
             StringBuilder logInfo = new StringBuilder("");
            string currentTime = System.DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]");
            if (ex != null)
             {
                logInfo.Append("\n");
                logInfo.Append(currentTime + "\n");
                 //获取描述当前的异常的信息
                 logInfo.Append(ex.Message + "\n");
                //获取当前实例的运行时类型
                 logInfo.Append(ex.GetType() + "\n");
                 //获取或设置导致错误的应用程序或对象的名称
                 logInfo.Append(ex.Source + "\n");
                 //获取引发当前异常的方法
                logInfo.Append(ex.TargetSite + "\n");
                 //获取调用堆栈上直接桢的字符串表示形式
                 logInfo.Append( ex.StackTrace + "\n");
             }
             System.IO.File.AppendAllText(appLogPath + DateTime.Now.ToString("yyyy-MM-dd") + ".log", logInfo.ToString());
         }
 
     }
 }

调用方法:

     try
             {
                 while (true)
                 {
                     int a = Convert.ToInt32(Console.ReadLine());
                     Console.WriteLine("您输入的是:" + a);
                 }
 
             }
             catch (Exception ex)
             {

                 LogHelper.WriteLog(ex);
             }
             Console.Write("OVER");
            Console.Read();
 }

 

posted @ 2017-06-06 12:03  韩梦芫  阅读(1292)  评论(0编辑  收藏  举报