C#之MVC中使用Log4Net

1 下载log4net.dll

 

2 在web.config 中的  <configSections>节点内增加如下代码

<!--log4net_s-->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<!--log4net_e-->

 

3 新增Config文件夹并增加log4net.config文件 具体配置可以自定义  示例内容如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  </configSections>
  <log4net debug="false">
    <!--错误日志配置-->
    <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="D:\\MyWebLog\\LogError\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="MaxFileSize" value="10240" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%n%d-------------------%n%m%n" />
      </layout>
    </appender>

    <!--信息日志配置-->
    <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="D:\\MyWebLog\\LogInfo\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxFileSize" value="10240" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%n%d-------------------%n%m%n" />
      </layout>
    </appender>

    <!--Debug日志配置-->
    <appender name="DebugAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="D:\\MyWebLog\\LogDebug\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxFileSize" value="10240" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d,%m%n" />
      </layout>
    </appender>

    <!--严重错误日志配置-->
    <appender name="FataAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="D:\\MyWebLog\\LogFata\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxFileSize" value="10240" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d,%m%n" />
      </layout>
    </appender>

    <!--警告日志配置-->
    <appender name="WarnAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="D:\\MyWebLog\\LogWarn\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxFileSize" value="10240" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d,%m%n" />
      </layout>
    </appender>
    <!--log4net.LogManager.GetLogger("logerror")用这个来选择这种类型-->
    <logger name="logerror">
      <level value="ERROR" />
      <appender-ref ref="ErrorAppender" />
    </logger>
    <logger name="loginfo">
      <level value="INFO" />
      <appender-ref ref="InfoAppender" />
    </logger>
    <logger name="logdebug">
      <level value="DEBUG" />
      <appender-ref ref="DebugAppender" />
    </logger>
    <logger name="logwarn">
      <level value="WARN" />
      <appender-ref ref="WarnAppender" />
    </logger>
    <logger name="logfata">
      <level value="FATA" />
      <appender-ref ref="FataAppender" />
    </logger>

  </log4net>
</configuration>

 

 

4 添加一个Log4NetHelper类库文件 内容如下:

public static class Log4NetHelper
    {
        private static string _debugAppender = "logdebug";
        private static string _errorAppender = "logerror";
        private static string _fatalAppender = "logfata";
        private static string _infoAppender = "loginfo";
        private static string _warnAppender = "logwarn";

        #region 属性设置
        /// <summary>
        /// 设置DebugAppender的值,默认为:logdebug
        /// </summary>
        public static string DebugAppender
        {
            set { _debugAppender = value; }
        }
        /// <summary>
        /// 设置ErrorAppender的值,默认为:logerror
        /// </summary>
        public static string ErrorAppender
        {
            set { _errorAppender = value; }
        }
        /// <summary>
        /// 设置FatalAppender的值,默认为:logfata
        /// </summary>
        public static string FatalAppender
        {
            set { _fatalAppender = value; }
        }
        /// <summary>
        /// 设置InfoAppender的值,默认为:loginfo
        /// </summary>
        public static string InfoAppender
        {
            set { _infoAppender = value; }
        }
        /// <summary>
        /// 设置WarnAppender的值,默认为:logwarn
        /// </summary>
        public static string WarnAppender
        {
            set { _warnAppender = value; }
        }
        #endregion

        /// <summary>
        /// 加载log4net的日志配置文件
        /// </summary>
        /// <param name="configFilePath">日志配置文件的完整路径</param>
        public static void LoadConfig(string configFilePath)
        {
            if (string.IsNullOrEmpty(configFilePath) || !File.Exists(configFilePath))
            {
                throw new ArgumentNullException("日志配置文件不存在");
            }
            XmlConfigurator.ConfigureAndWatch(new FileInfo(configFilePath));
        }

        /// <summary>
        /// 根据指定的日志适配器名称获取日志对象
        /// </summary>
        /// <param name="appenderName">日志适配器名称</param>
        /// <returns>日志对象</returns>
        private static ILog GetLogByName(string appenderName)
        {
            if (string.IsNullOrEmpty(appenderName))
            {
                throw new ArgumentNullException("日志配置名称不能为空");
            }
            return LogManager.GetLogger(appenderName);
        }

        /// <summary>
        /// 记录调试日志
        /// </summary>
        /// <param name="message">日志信息,如果因异常记录日志,则message可以为null</param>
        public static void Debug(string message)
        {
            ILog logByName = GetLogByName(_debugAppender);
            if (logByName.IsDebugEnabled)
            {
                logByName.Debug(message);
            }
        }

        /// <summary>
        /// 记录调试日志
        /// </summary>
        /// <param name="message">日志信息,如果因异常记录日志,则message可以为null</param>
        /// <param name="exception">为日志附加异常信息,可以在配置中获取更准确的信息,如无异常信息,则可以为null</param>
        public static void Debug(string message, Exception exception)
        {
            ILog logByName = GetLogByName(_debugAppender);
            if (logByName.IsDebugEnabled)
            {
                logByName.Debug(message, exception);
            }
        }

        /// <summary>
        /// 记录错误日志
        /// </summary>
        /// <param name="message">日志信息,如果因异常记录日志,则message可以为null</param>
        public static void Error(string message)
        {
            ILog logByName = GetLogByName(_errorAppender);
            if (logByName.IsErrorEnabled)
            {
                logByName.Error(message);
            }
        }

        /// <summary>
        /// 记录错误日志
        /// </summary>
        /// <param name="message">日志信息,如果因异常记录日志,则message可以为null</param>
        /// <param name="exception">为日志附加异常信息,可以在配置中获取更准确的信息,如无异常信息,则可以为null</param>
        public static void Error(string message, Exception exception)
        {
            ILog logByName = GetLogByName(_errorAppender);
            if (logByName.IsErrorEnabled)
            {
                logByName.Error(message, exception);
            }
        }

        /// <summary>
        /// 记录严重错误日志
        /// </summary>
        /// <param name="message">日志信息,如果因异常记录日志,则message可以为null</param>
        public static void Fatal(string message)
        {
            ILog logByName = GetLogByName(_fatalAppender);
            if (logByName.IsFatalEnabled)
            {
                logByName.Fatal(message);
            }
        }

        /// <summary>
        /// 记录严重错误日志
        /// </summary>
        /// <param name="message">日志信息,如果因异常记录日志,则message可以为null</param>
        /// <param name="exception">为日志附加异常信息,可以在配置中获取更准确的信息,如无异常信息,则可以为null</param>
        public static void Fatal(string message, Exception exception)
        {
            ILog logByName = GetLogByName(_fatalAppender);
            if (logByName.IsFatalEnabled)
            {
                logByName.Fatal(message, exception);
            }
        }

        /// <summary>
        /// 记录信息日志
        /// </summary>
        /// <param name="message">日志信息,如果因异常记录日志,则message可以为null</param>
        public static void Info(string message)
        {
            ILog logByName = GetLogByName(_infoAppender);
            if (logByName.IsInfoEnabled)
            {
                logByName.Info(message);
            }
        }

        /// <summary>
        /// 记录信息日志
        /// </summary>
        /// <param name="message">日志信息,如果因异常记录日志,则message可以为null</param>
        /// <param name="exception">为日志附加异常信息,可以在配置中获取更准确的信息,如无异常信息,则可以为null</param>
        public static void Info(string message, Exception exception)
        {
            ILog logByName = GetLogByName(_infoAppender);
            if (logByName.IsInfoEnabled)
            {
                logByName.Info(message, exception);
            }
        }

        /// <summary>
        /// 记录警告日志
        /// </summary>
        /// <param name="message">日志信息,如果因异常记录日志,则message可以为null</param>
        public static void Warn(string message)
        {
            ILog logByName = GetLogByName(_warnAppender);
            if (logByName.IsWarnEnabled)
            {
                logByName.Warn(message);
            }
        }

        /// <summary>
        /// 记录警告日志
        /// </summary>
        /// <param name="message">日志信息,如果因异常记录日志,则message可以为null</param>
        /// <param name="exception">为日志附加异常信息,可以在配置中获取更准确的信息,如无异常信息,则可以为null</param>
        public static void Warn(string message, Exception exception)
        {
            ILog logByName = GetLogByName(_warnAppender);
            if (logByName.IsWarnEnabled)
            {
                logByName.Warn(message, exception);
            }
        }

        
    }

 

5 在global.asax.cs 的Application_Start方法增加如下代码

 

//读取log4net的配置文件

Log4NetHelper.LoadConfig(AppDomain.CurrentDomain.BaseDirectory + "Config\\Log4net.config");

 

6 控制器action方法调用示例

 Log4NetHelper.Error("abc");

 Log4NetHelper.Info("abc");

 Log4NetHelper.Fatal("abc");

 Log4NetHelper.Debug("abc");

 Log4NetHelper.Warn("abc");

 

上一篇:java – log4j:ERROR setFile(null,false)调用失败


下一篇:asp.net core 集成 log4net 日志框架