C# web程序,winform程序,控制台程序配置log4net,使用log4net

第一添加log4net.config,这里配置包括信息提示写入,错误信息写入,控制台消息展示

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <log4net>
    <!--信息日志配置-->
    <appender name="infoAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Logs\Info\info.log" />
      <param name="AppendToFile" value="true" />
      <param name="MaxFileSize" value="10240" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="PreserveLogFileNameExtension" value="true" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyyMMdd" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <!--错误日志配置-->
    <appender name="errorAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Logs\Error\Err.log" />
      <param name="AppendToFile" value="true" />
      <param name="MaxFileSize" value="10240" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="PreserveLogFileNameExtension" value="true" />
      <param name="StaticLogFileName" value="false" />
      <param name="DatePattern" value="yyyyMMdd" />
      <param name="RollingStyle" value="Date" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <!-- 控制台前台显示日志 -->
    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="ERROR" />
        <foreColor value="Red, HighIntensity" />
      </mapping>
      <mapping>
        <level value="Info" />
        <foreColor value="Green" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" />
      </layout>

      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="Info" />
        <param name="LevelMax" value="Fatal" />
      </filter>
    </appender>
    <root>
      <!--配置日志的级别,低于此级别的就不写到日志里面去 None>Fatal>ERROR>WARN>DEBUG>INFO>ALL-->
      <level value="ALL" />
      <appender-ref ref="infoAppender" />
      <appender-ref ref="ColoredConsoleAppender" />
    </root>
    <logger name="loginfo">
      <level value="INFO" />
      <appender-ref ref="infoAppender" />
    </logger>
    <logger name="logerror">
      <level value="ERROR" />
      <appender-ref ref="errorAppender" />
    </logger>
  </log4net>
</configuration>

第二将log4net.config注入到log4net中

//Winform窗体程序或者控制台程序,加载log4net配置文件,以下代码是写在Program类的Main方法中
class Program
{ 
  static void Main(string[] args)
  {
    //加载log4net配置文件
    var filepath = AppDomain.CurrentDomain.BaseDirectory + "log4net.config";
    log4net.Config.XmlConfigurator.Configure(new FileInfo(filepath)); 
  }
}
//Web程序,加载Log4net配置文件 ,以下代码是写在Global.cs类中,例如
protected void Application_Start(object sender, EventArgs e)
{
  var configPath = HttpContext.Current.Server.MapPath("~/log4net.config");
  log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(configPath));
}

第三使用log4net SDK,去NUGET搜索log4net并加载到需要的项目中

/// <summary>
    /// 打印日志 
    /// </summary>
    public static class LogHelper
    {
        /// <summary>
        /// 打印提示
        /// </summary>
        /// <param name="txt"></param>
        public static void Info(string txt)
        {
            ILog log = log4net.LogManager.GetLogger("loginfo");
            log.Info(txt);
        }

        /// <summary>
        /// 打印提示
        /// </summary>
        /// <param name="txt"></param>
        public static void Info(string txt, Type type)
        {
            ILog log = log4net.LogManager.GetLogger(type);
            log.Info(txt);
        }

        /// <summary>
        /// 打印错误
        /// </summary>
        /// <param name="msg"></param>
        public static void Error(string msg)
        {
            ILog log = log4net.LogManager.GetLogger("logerror");
            log.Error(msg);
        }
        /// <summary>
        /// 打印错误
        /// </summary>
        /// <param name="msg"></param>
        public static void Error(string msg, Exception ex)
        {
            ILog log = log4net.LogManager.GetLogger("logerror");
            log.Error(msg, ex);
        }
    }

代码使用例子

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        string a = "FF";
        int b = Convert.ToInt32(a);
    }
    catch (Exception ex){
        LogHelper.Error(ex.Message.ToString(), ex);
    }
}

拿去,不谢!!!

posted @ 2020-10-16 14:45  Hello,Code  阅读(248)  评论(0编辑  收藏  举报