c#简单自定义异常处理日志辅助类
生活随笔
收集整理的這篇文章主要介紹了
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();}?
總結
以上是生活随笔為你收集整理的c#简单自定义异常处理日志辅助类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: USACO SECTION 1.1.2
- 下一篇: C#读书笔记:线程,任务和同步