using System; using System.Text; using log4net; namespace Logger { /// /// 日志 /// public class LogHelper { /// /// 日志对象 /// private static ILog _log; /// /// 构造 /// /// 日志對象 public LogHelper(Type type) { //FileInfo configFile = new FileInfo(HttpContext.Current.Server.MapPath("/XmlConfig/log4net.config")); //log4net.Config.XmlConfigurator.Configure(configFile); _log = LogManager.GetLogger(type); } /// /// 构造 /// /// public LogHelper(string typeName) { //FileInfo configFile = new FileInfo(HttpContext.Current.Server.MapPath("/XmlConfig/log4net.config")); //log4net.Config.XmlConfigurator.Configure(configFile); _log = LogManager.GetLogger(typeName); } /// /// 得到日志对象 /// /// /// public static ILog GetLogger(string type) { return LogManager.GetLogger(type); } /// /// 利用Action委托封装Log4net对日志的处理,无返回值 /// /// 类型 /// 描述 /// 异常处理方式 /// 调试代码 /// 异常处理方式 /// 最终处理方式 public static void Logger(Type type, string desc, ErrorHandel errorHandel, Action tryHandel,Action catchHandel = null, Action finallHandel = null) { ILog log = LogManager.GetLogger(type); try { //log.Debug(desc + "\r\n"); tryHandel(); } catch (Exception exception) { //StringBuilder builder = new StringBuilder(); //builder.Append("\r\n==========================" + desc + "发生异常==========================\r\n"); //builder.Append(string.Format("发生时间:{0:yyyy-MM-dd HH:mm:ss}\r\n", DateTime.Now)); //builder.Append(string.Format("错误描述:{0}\r\n", exception.Message.Replace("\r\n", ""))); //builder.Append(string.Format("错误对象:{0}\r\n", exception.Source)); //builder.Append(string.Format("引发当前异常方法:{0}\r\n", exception.TargetSite)); //builder.Append("\r\n==========================异常信息结束==========================\r\n"); log.Error(desc + "发生异常。", exception); if (catchHandel != null) { catchHandel(exception); } if (errorHandel == ErrorHandel.Throw) { throw; } } finally { if (finallHandel != null) { finallHandel(); } } } #region 1、Info /// /// 普通日志 /// /// public void Info(string info) { _log.Info(info); } /// /// 普通日志,带参数 /// /// /// public void InfoFormat(string format, params object[] args) { _log.InfoFormat(format, args); } #endregion #region 2、Error /// /// 错误日志 /// /// public void Error(string info) { _log.Error(info); } /// /// 异常日志 /// /// /// public void Error(string info, Exception exception) { _log.Error(info, exception); } /// /// 错误日志,带参数 /// /// /// public void ErrorFormat(string format, params object[] args) { _log.ErrorFormat(format, args); } #endregion #region 3、Debug /// /// 调试日志 /// /// public void Debug(string info) { _log.Debug(info); } /// /// 调试日志,带参数 /// /// /// public void DebugFormat(string format, params object[] args) { _log.DebugFormat(format, args); } #endregion #region 4、Warn /// /// 警告日志 /// /// public void Warn(string info) { _log.Warn(info); } /// /// 警告日志,带参数 /// /// /// public void WarnFormat(string format, params object[] args) { _log.WarnFormat(format, args); } #endregion } }