asp.net 页面中引用log4net,添加日志操作

  最近在一个项目中使用到了log4net.dll用于记录操作日志,从网上找的大部分资料都是在每个需要输出日志的类中都先声明一下,然后再调用它的输出函数,如debug,error等等

如果是一个小的项目,这样比较简单,使用起来很容易,但是如果项目涉及多个解决方案,比如我现在的贸易系统项目,每天的流水会达到几个亿,会涉及多个操作类型,因此就需要有详细的日志记录信息,

如果还用以前的方式会比较麻烦,因此就按照项目需要,单独创建一个dll用于实现记录日志。

 

1、下载一个log4net.dll

2、创建一个类库如:LogUtility,添加log4net.dll的引用

    添加一个类LogHelper.cs,用于执行日志写入

  

public class LogHelper
    {
        private const string m_ConfigName = "log4net.config";

        static LogHelper()
        {
            InitConfig();
        }

        public static void WriteLog(LogLevelType logLevel, object message)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            DoWriteLog(log, logLevel, message);
        }

        public static void WriteLog(string logAreaName, LogLevelType logLevel, object message)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(logAreaName);
            DoWriteLog(log, logLevel, message);
        }
        public static void WriteLog(LogLevelType logLevel, object message, Exception exception)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            DoWriteLog(log, logLevel, message, exception);
        }

        public static void WriteLog(string logAreaName, LogLevelType logLevel, object message, Exception exception)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(logAreaName);
            DoWriteLog(log, logLevel, message, exception);
        }

        public static void InitConfig()
        {
            log4net.Config.XmlConfigurator.Configure();
        }

        /// <summary>
        /// 初始化配置信息
        /// </summary>
        /// <param name="configFile">log4net.config路径</param>
        public static void InitConfig(string configFile)
        {
            if (System.IO.File.Exists(configFile))
            {
                log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(configFile));
            }
        }

        public static log4net.ILog GetLogger(string logName)
        {
            log4net.ILog log = log4net.LogManager.GetLogger(logName);
            return log;
        }

        private static void DoWriteLog(ILog log, LogLevelType logLevel, object message)
        {
            switch (logLevel)
            {
                case LogLevelType.DEBUG:
                    if (log.IsDebugEnabled)
                    {
                        log.Debug(message);
                    }
                    break;
                case LogLevelType.INFO:
                    if (log.IsInfoEnabled)
                    {
                        log.Info(message);
                    }
                    break;
                case LogLevelType.WARN:
                    if (log.IsWarnEnabled)
                    {
                        log.Warn(message);
                    }
                    break;
                case LogLevelType.ERROR:
                    if (log.IsErrorEnabled)
                    {
                        log.Error(message);
                    }
                    break;
                case LogLevelType.FATAL:
                    if (log.IsFatalEnabled)
                    {
                        log.Fatal(message);
                    }
                    break;
                default:
                    break;
            }
        }
        private static void DoWriteLog(ILog log, LogLevelType logLevel, object message, Exception exception)
        {
            switch (logLevel)
            {
                case LogLevelType.DEBUG:
                    if (log.IsDebugEnabled)
                    {
                        log.Debug(message, exception);
                    }
                    break;
                case LogLevelType.INFO:
                    if (log.IsInfoEnabled)
                    {
                        log.Info(message, exception);
                    }
                    break;
                case LogLevelType.WARN:
                    if (log.IsWarnEnabled)
                    {
                        log.Warn(message, exception);
                    }
                    break;
                case LogLevelType.ERROR:
                    if (log.IsErrorEnabled)
                    {
                        log.Error(message, exception);
                    }
                    break;
                case LogLevelType.FATAL:
                    if (log.IsFatalEnabled)
                    {
                        log.Fatal(message, exception);
                    }
                    break;
                default:
                    break;
            }
        }

  还需要添加一个日志级别的类LogLevelType.cs 用于区分日志的类型

    /// <summary>
    /// 日志级别
    /// </summary>
    public enum LogLevelType
    {
        DEBUG = 1,
        INFO = 2,
        WARN = 3,
        ERROR = 4,
        FATAL = 5
    }

  由于项目涉及多个解决方案,还需要创建一个类LogArea:用于区分日志的使用区域

      /// <summary>
      /// 日志区域
    /// </summary>
    public class LogArea
    {
        /// <summary>
        /// 系统管理
        /// </summary>
        public const string SYSTEM = "SYSTEM";

        //等等
    }

 

3、在Web解决方案中,引用刚刚创建的dll,并且添加log4net.config文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
  </configSections>
  
  <log4net>
    <appender name="PmsLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="Logs\%date{yyyy-MM}\AllLogs\ALL_%date{yyyy-MM-dd}.log" />
      <appendToFile value="true" />
      <datePattern value="yyyy-MM-dd" />
      <rollingStyle value="Date" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>

    <root>
      <!--level级别:ALL<DEBUG<INFO<WARN<ERROR<FATAL<OFF -->
      <level value="ERROR"/>
      <appender-ref ref="PmsLogFileAppender" />
    </root>

    <logger name="SYSTEM">
      <level value="ERROR"/>
      <appender-ref ref="PmsLogFileAppender" />
    </logger>
  </log4net>
</configuration>

  在项目中AssemblyInfo.cs添加

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]

  

4、在需要添加日志的方法中,引用dll

/// <summary>
        /// 根据用户名与密码检查登录用户是否存在
        /// </summary>
        /// <param name="UserID">用户名</param>
        /// <param name="PassWord">用户密码</param>
        /// <returns>返回查询用户存在真值</returns>
        public bool CheckUser(string UserID, string PassWord)
        {
            DBHelper db = new DBHelper();		//通用数据操作类
            SqlParameter[] prams = {
										db.MakeInParam("@UserID", SqlDbType.VarChar, 20, UserID),
										db.MakeInParam("@Password", SqlDbType.VarChar, 20, PassWord),
									};
            try
            {
                int intReturnValue = db.ExecuteProc("Wygl_System_UserAuthorization_CheckLoginUser", prams);
                return intReturnValue == 1 ? true : false;
            }
            catch//(Exception exc)
            {
                LogHelper.WriteLog(LogArea.SYSTEM, LogLevelType.ERROR, "系统警告:检验登录用户过程中出错!");
                return false;
            }
        }

  即可

 效果图:

 技术分享

首次使用,如果有错误,请理解,谢谢

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。