工程异常日志管理方案

一、工程错误日志管理方案设计

主要采用SystemInfo.ini设备文件存储标识:

DEBUG状态弹出异常;

RELEASE状态直接将异常信息写入日志文件而不弹出窗口。

image

 

调试状态下,

[Setting]
IsShowException=True

运行效果:

image

发布状态下,

[Setting]
IsShowException=False

运行效果:

image

 

二、关键类设计

CIniFileIO.cs类用于读INI文件的IsShowException关键字

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Runtime.InteropServices;

  6. namespace TestGetSelfNameAPI
  7. {
  8.     public class CIniFileIO
  9.     {
  10.         [DllImport("kernel32")]
  11.         private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
  12.         [DllImport("kernel32")]
  13.         private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
  14.         [DllImport("kernel32")]
  15.         private static extern int GetPrivateProfileString(string section, string key, string def, byte[] BufferRe, uint size, string FilePath);


  16.         #region =============-------Write and Read IsShowException ---------================
  17.         public static bool GetIsShowException()
  18.         {
  19.             bool isShow = true;
  20.             FileInfo sysInfo = new FileInfo(System.Windows.Forms.Application.StartupPath + "\\SystemInfo.ini");
  21.             string sectionName = "Setting";
  22.             string keyName = "IsShowException";
  23.             string truthValue = "True";

  24.             if (sysInfo.Exists)
  25.             {
  26.                 StringBuilder strBuilder = new StringBuilder(255);
  27.                 GetPrivateProfileString(sectionName, keyName, "", strBuilder, 255, sysInfo.ToString().Trim());
  28.                 truthValue = strBuilder.ToString();
  29.                 if (truthValue.Equals("True"))
  30.                     isShow = true;
  31.                 else
  32.                     isShow = false;
  33.             }

  34.             return isShow;
  35.         }

  36.         public static void WriteIsShowException(bool isShowException)
  37.         {
  38.             /* 为DayaSystemInof.ini文件写进信息,来进行登记 */
  39.             string iniFilePath = System.Windows.Forms.Application.StartupPath + "\\SystemInfo.ini";
  40.             string sectionName = "Setting";
  41.             string keyName = "IsShowException";
  42.             string truthValue = "True";

  43.             if (isShowException)
  44.                 truthValue = "True";
  45.             else
  46.                 truthValue = "False";
  47.             string keyValue = truthValue;
  48.             WritePrivateProfileString(sectionName, keyName, keyValue, iniFilePath);
  49.         }
  50.         #endregion
  51.     }
  52. }



CLogManager.cs用于写错误日志文件

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Threading;
  6. using System.Net;
  7. using System.Windows.Forms;
  8. using System.Web;
  9. using System.Diagnostics;

  10. namespace TestGetSelfNameAPI
  11. {
  12.     ///
  13.     /// 通过检测DayaSystemInfo.ini目录下的IsShowException关键字
  14.     /// 以决定是否弹出异常
  15.     ///
  16.     public class CLogManager
  17.     {
  18.         private static string mLogFilePath = null;
  19.         private static object mConcreteObject = new object();
  20.         private static string mStrExecutePath = null;
  21.         private static StreamWriter mLogStringWriter = null;
  22.         private static short mLoggerLevel = 0;

  23.         static CLogManager()
  24.         {
  25.             mStrExecutePath = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf(@"\") + 1);
  26.             if (!Directory.Exists(mStrExecutePath + "LogMessage"))
  27.             {
  28.                 Directory.CreateDirectory(mStrExecutePath + "LogMessage");
  29.             }
  30.             mLogFilePath = (mStrExecutePath + @"LogMessage\ExceptionRecordLog.txt");

  31.             if (!File.Exists(mLogFilePath))
  32.             {
  33.                 FileStream fs = File.Create(mLogFilePath);
  34.                 fs.Dispose();
  35.                 fs.Close();
  36.             }
  37.             try
  38.             {
  39.                 string level = System.Configuration.ConfigurationSettings.AppSettings["mLoggerLevel"];
  40.                 mLoggerLevel = short.Parse(level);
  41.             }
  42.             catch
  43.             {
  44.                 mLoggerLevel = 0;
  45.             }
  46.         }

  47.         ///
  48.         /// delete logs which have not been updated for more than 15 days
  49.         ///
  50.         public static void LogClean()
  51.         {
  52.             /* 获取十五天前的日期 */
  53.             string fifteenDaysbefore = DateTime.Now.AddDays(-15.0).ToString("yyyyMMdd");
  54.             string fiveminutebefore = DateTime.Now.AddMinutes(-5.0).ToString("yyyyMMddHHmmSS");
  55.             /* 应用程序目录+LogMessage文件夹 */
  56.             string[] logs = Directory.GetFiles(mStrExecutePath + "LogMessage");

  57.             foreach (string log in logs)
  58.             {
  59.                 System.IO.FileInfo info = new FileInfo(log);

  60.                 if (info.LastWriteTime.ToString("yyyyMMdd").CompareTo(fifteenDaysbefore)
  61.                 {
  62.                     try
  63.                     {
  64.                         File.Delete(log);
  65.                     }
  66.                     catch { }
  67.                 }
  68.             }
  69.         }


  70.         ///
  71.         /// ExceptionHandle 重载函数一
  72.         ///
  73.         public static void ExceptionHandle(string csFileName, string funcName, Exception exceptionName)
  74.         {
  75.             /* 同步访问对象方式 */
  76.             Monitor.Enter(mConcreteObject);
  77.             /* 创建前一天的日期文件(名) */
  78.             string strLogBakPath = mStrExecutePath + @"LogMessage\" + DateTime.Now.AddDays(-1.0).ToString("yyyyMMdd") + ".txt";

  79.             if (!File.Exists(strLogBakPath))
  80.             {
  81.                 /* Copy是非覆盖拷贝,所以要做文件存在性的判断
  82.                  取mLogFilePath,代表全局静态的NetConnectorLog.txt文件的值给前天的日期文件!*/
  83.                 File.Copy(mLogFilePath, strLogBakPath);
  84.             }

  85.             /* mLogStringWriter是一个IO流对象,没有就创建一个StreamWriter;*/
  86.             if (mLogStringWriter == null)
  87.             {
  88.                 /* 取mLogFilePath上的文件,生成一个bak备份文件 */
  89.                 strLogBakPath = mStrExecutePath + @"LogMessage\" + DateTime.Now.ToString("yyyyMMddHHmmsss") + ".txt.bak";
  90.                 File.Copy(mLogFilePath, strLogBakPath);
  91.                 try
  92.                 {
  93.                     mLogStringWriter = new StreamWriter(mLogFilePath);
  94.                 }
  95.                 catch { }
  96.             }
  97.             try
  98.             {
  99.                 mLogStringWriter.WriteLine("Exceptoin occurred in " + csFileName + "'s " + funcName + "() At " + string.Format("{0}", DateTime.Now.ToString()) + ">");
  100.                 mLogStringWriter.WriteLine("**********************************************************************************************************************");
  101.                 mLogStringWriter.WriteLine(string.Format("{0}", exceptionName.ToString()));
  102.                 mLogStringWriter.WriteLine("----------------------------------------------------------------------------------------------------------------------");
  103.                 mLogStringWriter.WriteLine();
  104.                 mLogStringWriter.WriteLine();
  105.                 mLogStringWriter.Flush();
  106.             }
  107.             finally
  108.             {
  109.                 /* 释放排他锁 */
  110.                 Monitor.Exit(mConcreteObject);
  111.             }
  112.         }

  113.         ///
  114.         /// 接收上层传进来的异常信息
  115.         ///
  116.         /// 包含发生异常的函数名及所有的文件的名称
  117.         /// 整个异常的信息
  118.         public static void SendException(StackTrace st, Exception exceptionName)
  119.         {
  120.             string csFileName = string.Empty;
  121.             string fileFullName = string.Empty;
  122.             string methodName = string.Empty;

  123.             StackFrame sf = st.GetFrame(0);
  124.             fileFullName = sf.GetFileName();
  125.             csFileName = fileFullName.Substring(fileFullName.LastIndexOf('\\') + 1);
                methodName = sf.GetMethod().Name;


                if (CIniFileIO.GetIsShowException())
                    MessageBox.Show(exceptionName.ToString());
                else
                {
                    ExceptionHandle(csFileName, methodName, exceptionName);
                    LogClean();
                }
            }




            public static void DirectWirteErrorToLog(string csFileName, string methodName, Exception exceptionName)
            {
                ExceptionHandle(csFileName, methodName, exceptionName);
                LogClean();
            }


        }
    }
源工程代码:
img_e25d4fb2f8de1caf41a735ec53088516.pngTestGetSelfNameAPI.rar


三、参考文献

获取当前函数名及函数所在的文件

http://www.cnblogs.com/hyddd/articles/1500808.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值