C# log4net使用案例詳解

這邊先介紹簡單的使用:在控制臺輸出和寫入文件

首先添加log4net的nuget包

然後在app.config中添加配置項==configSections隻能有一個,且是configuration的首個節點

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <log4net>
    <root>
      <level value="WARN" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="ConsoleAppender" />
    </root>

    <logger name="testApp.Logging">
      <level value="DEBUG"/>
    </logger>

    <appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
      <param name="File" value="log_file.txt" />
      <!--<param name="File" value="D:/log_file.txt" />-->
      <param name="AppendToFile" value="true" />

      <layout type="log4net.Layout.PatternLayout">
        <!--<param name="Header" value="[Header] "/>
        <param name="Footer" value="[Footer] "/>-->
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>

      <filter type="log4net.Filter.LevelRangeFilter">
        <param name="LevelMin" value="DEBUG" />
        <param name="LevelMax" value="WARN" />
      </filter>
    </appender>
    
    <appender name="ConsoleAppender"  type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern"  value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
  </log4net>
</configuration>

這部分代碼也可以單獨放在一個配置文件中,起名log4net.config,我們把這個文件和app.config放在同一層

接著在AssemblyInfo.cs下添加特性

//配置文件在app.config中
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
//配置文件在log4net.config中
//[assembly: log4net.Config.XmlConfigurator(ConfigFile="log4net.config", Watch = true)]
Watch=true監視配置文件,當配置文件發生變化的時候,就會重新加載。
static void Main(string[] args)
{
    log4net.ILog log = log4net.LogManager.GetLogger("testApp.Logging");//獲取一個日志記錄器

    //配置文件在app.config中
    log4net.Config.XmlConfigurator.Configure();
    //配置文件在log4net.config中
    //string assemblyFilePath = Assembly.GetExecutingAssembly().Location;
    //string assemblyDirPath = Path.GetDirectoryName(assemblyFilePath);
    //DirectoryInfo pathInfo = new DirectoryInfo(assemblyDirPath);
    //string configFilePath = pathInfo.Parent.Parent.FullName + "//log4net.config";
    //log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(configFilePath));
    //絕對路徑
    //log4net.Config.XmlConfigurator.Configure(newSystem.IO.FileInfo(@"E:/DEMO/Log4NetDemo/emoTest/log4net.config"));
    
    Thread.CurrentThread.Name = "main";
    log.Debug("初始化連接開始");
    log.Warn("測試");
    log.Info(DateTime.Now.ToString() + ": login success");
    
    Console.ReadKey();
}

到此這篇關於C# log4net使用案例詳解的文章就介紹到這瞭,更多相關Java log4net使用內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: