2023年6月21日发(作者:)
C#简易异步⽇志类前⾔ 即使是⼩型项⽬,也需要⽇志的功能,这⾥就不讨论Log4Net之类的框架,提供⼀个异步的、控制台输出+⽇志⽂件输出的简易⽇志帮助类。
正⽂ ⼀、帮助类⽂件//=========================================//// 作 者:农民伯伯// 邮 箱:over140@// 博 客:/// 时 间:2009-7-16// 描 述:⽇志类,注意需要在⽇志记录的⽬录给⽤户写⼊权限!////=========================================using System;using uration;using c;using ent;using stics;using ;using ;using erServices;using ;namespace CentralHousesTest{ /// /// ⽇志类 /// public sealed class Logger { #region Member Variables /// /// ⽤于Trace的组织输出的类别名称 /// private const string trace_sql = "rn***********************TRACE_SQL {0}*****************************rnTRACE_SQL"; /// /// ⽤于Trace的组织输出的类别名称 /// private const string trace_exception = "rn***********************TRACE_EXCEPTION {0}***********************"; /// /// 当前⽇志的⽇期 /// private static DateTime CurrentLogFileDate = ; /// /// ⽇志对象 /// private static TextWriterTraceListener twtl; /// /// ⽇志根⽬录 /// private const string log_root_directory = @"D:log"; /// /// ⽇志⼦⽬录 /// private static string log_subdir; /// /// " {0} = {1}" /// private const string FORMAT_TRACE_PARAM = " {0} = {1}"; /// /// 1 仅控制台输出 /// 2 仅⽇志输出 /// 3 控制台+⽇志输出 /// private static readonly int flag = 2; //可以修改成从配置⽂件读取 #endregion #region Constructor static Logger() { ush = true; switch (flag) { case 1: (new ConsoleTraceListener()); break; case 2: (TWTL); break; case 3: (new ConsoleTraceListener()); (TWTL); break; } } #endregion #region Method #region trace /// /// 异步错误⽇志 /// /// public static void Trace(Exception ex) { new AsyncLogException(BeginTraceError).BeginInvoke(ex, null, null); } /// /// 异步SQL⽇志 /// /// public static void Trace(SqlCommand cmd) { new AsyncLogSqlCommand(BeginTraceSqlCommand).BeginInvoke(cmd, null, null); } /// /// 异步SQL⽇志 /// /// /// public static void Trace(string sql, params SqlParameter[] parameter) { new AsyncLogSql(BeginTraceSql).BeginInvoke(sql, parameter, null, null); } #endregion #region delegate private delegate void AsyncLogException(Exception ex); private delegate void AsyncLogSqlCommand(SqlCommand cmd); private delegate void AsyncLogSql(string sql, params SqlParameter[] parameter); private static void BeginTraceError(Exception ex) { if (null != ex) { //检测⽇志⽇期 StrategyLog(); //输出⽇志头 ine((trace_exception, )); while (null != ex) { ine(("{0} {1}rn{2}rnSource:{3}", e().Name, e, race, )); ex = xception; } } } private static void BeginTraceSqlCommand(SqlCommand cmd) { if (null != cmd) { SqlParameter[] parameter = new SqlParameter[]; (parameter, 0); BeginTraceSql(dText, parameter); } } private static void BeginTraceSql(string sql, params SqlParameter[] parameter) { if (!OrEmpty(sql)) { //检测⽇志⽇期 StrategyLog(); ine(sql, (trace_sql, )); if (parameter != null) { foreach (SqlParameter param in parameter) { ine((FORMAT_TRACE_PARAM, terName, )); } } } } } #endregion #region helper /// /// 根据⽇志策略⽣成⽇志 /// private static void StrategyLog() { //判断⽇志⽇期 if (e(, ) != 0) { DateTime currentDate = ; //⽣成⼦⽬录 BuiderDir(currentDate); //更新当前⽇志⽇期 CurrentLogFileDate = currentDate; (); //更改输出 if (twtl != null) (twtl); (TWTL); } } /// /// 根据年⽉⽣成⼦⽬录 /// /// private static void BuiderDir(DateTime currentDate) { int year = ; int month = ; //年/⽉ string subdir = (year, '', month); string path = e(log_root_directory, subdir); if (!(path)) { Directory(path); } log_subdir = subdir; } #endregion #endregion #region Properties /// /// ⽇志⽂件路径 /// /// private static string GetLogFullPath { get { return (log_root_directory, '', (log_subdir, @"log", tDateString(), ".txt")); } } } /// /// 跟踪输出⽇志⽂件 /// private static TextWriterTraceListener TWTL { get { if (twtl == null) { if (OrEmpty(log_subdir)) BuiderDir(); else { string logPath = GetLogFullPath; if (!(ectoryName(logPath))) BuiderDir(); } twtl = new TextWriterTraceListener(GetLogFullPath); } return twtl; } } #endregion }}
⼆、⽰例 2.1 错误记录static void Main(string[] args) { IList list = null; try { ine(); } catch (Exception ex) { (ex); } ne(); }代码说明:错误很明显,未实例化就使⽤Count属性。 ⽇志截图:
2.2 数据库记录using (SqlConnection con = new SqlConnection("Data Source=OVERA;Initial Catalog=Northwind;User ID=sa;Password=sa;")) { (); SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Customers WHERE CompanyName = @CompanyName", con); (new SqlParameter("@CompanyName", "Alfreds Futterkiste")); (sqlCmd); SqlDataReader sdr = eReader(); while (()) { (e(1)); (" : "); ine( sdr[1]);
} (); } ne(); } ⽇志截图: 需要注意这⾥⽇志策略改为了仅⽇志⽂件输出。 三、注意事项 3.1 进⾏⽇志⽂件输出的时候需要有写的权限。 3.2 实际使⽤中可能还会有⼀个变量控制是否进⾏⽇志记录。 3.3 错误记录⼀般会在的Application_Error⾥⾯加上。
结束语 对于⼀般的⼩项⽬这个⽇志类是够⽤的了,⽇志的策略还可以根据⾃⼰的需求改变⼀下,合适就⾏: )
2023年6月21日发(作者:)
C#简易异步⽇志类前⾔ 即使是⼩型项⽬,也需要⽇志的功能,这⾥就不讨论Log4Net之类的框架,提供⼀个异步的、控制台输出+⽇志⽂件输出的简易⽇志帮助类。
正⽂ ⼀、帮助类⽂件//=========================================//// 作 者:农民伯伯// 邮 箱:over140@// 博 客:/// 时 间:2009-7-16// 描 述:⽇志类,注意需要在⽇志记录的⽬录给⽤户写⼊权限!////=========================================using System;using uration;using c;using ent;using stics;using ;using ;using erServices;using ;namespace CentralHousesTest{ /// /// ⽇志类 /// public sealed class Logger { #region Member Variables /// /// ⽤于Trace的组织输出的类别名称 /// private const string trace_sql = "rn***********************TRACE_SQL {0}*****************************rnTRACE_SQL"; /// /// ⽤于Trace的组织输出的类别名称 /// private const string trace_exception = "rn***********************TRACE_EXCEPTION {0}***********************"; /// /// 当前⽇志的⽇期 /// private static DateTime CurrentLogFileDate = ; /// /// ⽇志对象 /// private static TextWriterTraceListener twtl; /// /// ⽇志根⽬录 /// private const string log_root_directory = @"D:log"; /// /// ⽇志⼦⽬录 /// private static string log_subdir; /// /// " {0} = {1}" /// private const string FORMAT_TRACE_PARAM = " {0} = {1}"; /// /// 1 仅控制台输出 /// 2 仅⽇志输出 /// 3 控制台+⽇志输出 /// private static readonly int flag = 2; //可以修改成从配置⽂件读取 #endregion #region Constructor static Logger() { ush = true; switch (flag) { case 1: (new ConsoleTraceListener()); break; case 2: (TWTL); break; case 3: (new ConsoleTraceListener()); (TWTL); break; } } #endregion #region Method #region trace /// /// 异步错误⽇志 /// /// public static void Trace(Exception ex) { new AsyncLogException(BeginTraceError).BeginInvoke(ex, null, null); } /// /// 异步SQL⽇志 /// /// public static void Trace(SqlCommand cmd) { new AsyncLogSqlCommand(BeginTraceSqlCommand).BeginInvoke(cmd, null, null); } /// /// 异步SQL⽇志 /// /// /// public static void Trace(string sql, params SqlParameter[] parameter) { new AsyncLogSql(BeginTraceSql).BeginInvoke(sql, parameter, null, null); } #endregion #region delegate private delegate void AsyncLogException(Exception ex); private delegate void AsyncLogSqlCommand(SqlCommand cmd); private delegate void AsyncLogSql(string sql, params SqlParameter[] parameter); private static void BeginTraceError(Exception ex) { if (null != ex) { //检测⽇志⽇期 StrategyLog(); //输出⽇志头 ine((trace_exception, )); while (null != ex) { ine(("{0} {1}rn{2}rnSource:{3}", e().Name, e, race, )); ex = xception; } } } private static void BeginTraceSqlCommand(SqlCommand cmd) { if (null != cmd) { SqlParameter[] parameter = new SqlParameter[]; (parameter, 0); BeginTraceSql(dText, parameter); } } private static void BeginTraceSql(string sql, params SqlParameter[] parameter) { if (!OrEmpty(sql)) { //检测⽇志⽇期 StrategyLog(); ine(sql, (trace_sql, )); if (parameter != null) { foreach (SqlParameter param in parameter) { ine((FORMAT_TRACE_PARAM, terName, )); } } } } } #endregion #region helper /// /// 根据⽇志策略⽣成⽇志 /// private static void StrategyLog() { //判断⽇志⽇期 if (e(, ) != 0) { DateTime currentDate = ; //⽣成⼦⽬录 BuiderDir(currentDate); //更新当前⽇志⽇期 CurrentLogFileDate = currentDate; (); //更改输出 if (twtl != null) (twtl); (TWTL); } } /// /// 根据年⽉⽣成⼦⽬录 /// /// private static void BuiderDir(DateTime currentDate) { int year = ; int month = ; //年/⽉ string subdir = (year, '', month); string path = e(log_root_directory, subdir); if (!(path)) { Directory(path); } log_subdir = subdir; } #endregion #endregion #region Properties /// /// ⽇志⽂件路径 /// /// private static string GetLogFullPath { get { return (log_root_directory, '', (log_subdir, @"log", tDateString(), ".txt")); } } } /// /// 跟踪输出⽇志⽂件 /// private static TextWriterTraceListener TWTL { get { if (twtl == null) { if (OrEmpty(log_subdir)) BuiderDir(); else { string logPath = GetLogFullPath; if (!(ectoryName(logPath))) BuiderDir(); } twtl = new TextWriterTraceListener(GetLogFullPath); } return twtl; } } #endregion }}
⼆、⽰例 2.1 错误记录static void Main(string[] args) { IList list = null; try { ine(); } catch (Exception ex) { (ex); } ne(); }代码说明:错误很明显,未实例化就使⽤Count属性。 ⽇志截图:
2.2 数据库记录using (SqlConnection con = new SqlConnection("Data Source=OVERA;Initial Catalog=Northwind;User ID=sa;Password=sa;")) { (); SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Customers WHERE CompanyName = @CompanyName", con); (new SqlParameter("@CompanyName", "Alfreds Futterkiste")); (sqlCmd); SqlDataReader sdr = eReader(); while (()) { (e(1)); (" : "); ine( sdr[1]);
} (); } ne(); } ⽇志截图: 需要注意这⾥⽇志策略改为了仅⽇志⽂件输出。 三、注意事项 3.1 进⾏⽇志⽂件输出的时候需要有写的权限。 3.2 实际使⽤中可能还会有⼀个变量控制是否进⾏⽇志记录。 3.3 错误记录⼀般会在的Application_Error⾥⾯加上。
结束语 对于⼀般的⼩项⽬这个⽇志类是够⽤的了,⽇志的策略还可以根据⾃⼰的需求改变⼀下,合适就⾏: )
发布评论