码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-06-06 13:07:41      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:adl   tostring   实例   ted   generic   pat   names   domain   str   

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

 

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

标签:adl   tostring   实例   ted   generic   pat   names   domain   str   

原文地址:http://www.cnblogs.com/siyunianhua/p/6950835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!