首页 > Windows开发 > 详细

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

时间:2017-06-06 12:31:54      阅读:233      评论:0      收藏:0      [点我收藏+]
 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#简单自定义异常处理日志辅助类

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!