C# Log4Net Learning Notes: Log to File

Posted by shane85 on Mon, 11 May 2020 18:40:47 +0200

1. Basic knowledge

1.1. Introduction

Log4Net is an open source logging framework that is powerful enough to classify logs into different levels and output them to different storage media in different formats, such as databases, txt files, memory buffers, mail, consoles, ANSI terminals, remote receivers, and so on.

Log4Net divides logs into five levels, from high to low: FATAL (fatal error), ERROR (general error), WARN (warning), INFO (general information), DEBUG (debug information).

Log4Net has four main components, Logger, Repository, Appender, and Layout.

1.2, Download

    Official Address  GitHub address

2. Record log to file

2.1, Log4Net installation

Create a new console application, right-click the project - > Manage NuGet Package - > log4net.

2.2, Profile

Add a ConfigFile folder, create a new Log4NetToFile.config configuration file under it, and then choose Always Copy under the output directory for copying its properties.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <!--type: Indicates what type of log is used. log4net.Appender.RollingFileAppender Represents logging in text.-->
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    
      <!--Log Storage Path-->
      <file value="Log\" />
    
      <!--Whether to append logs-->
      <appendToFile value="true" />
    
      <!--Prevent Writing When Multithreaded Log,Officially, threads are unsafe.-->
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    
      <!--To configure Unicode Code-->
      <encoding value="utf-8" />
    
      <!--Write to only one file-->
      <staticLogFileName value="false" />
    
      <!--Add a suffix to the file name, which can be used as: Generate with date as file name log. -->
      <datePattern value="yyyyMMdd'.txt'" />
    
      <!--Can be: Once|Size|Date|Composite-->
      <!--Composite by Size and Date Combination-->
      <rollingStyle value="Composite" />
      
      <!--Maximum number of logs, keeping only the latest.-->
      <!--rollingStyle Node is Size Only when value Log files.-->
      <!--rollingStyle Node is Composite When, you can only have value Log files.-->
      <maxSizeRollBackups value="2" />
      
      <!--Available units: KB|MB|GB-->
      <maximumFileSize value="2MB" />
      
      <!--Filter-->
      
      <!--Reject log output used(Logging switch)-->
      <!--<filter type="log4net.Filter.DenyAllFilter" />-->
      
      <!--Only log events of a specified level are logged-->
      <!--<filter type="log4net.Filter.LevelMatchFilter">
        <AcceptOnMatch value="true" />
        <param name="levelToMatch" value="DEBUG" />
      </filter>
      <filter type="log4net.Filter.DenyAllFilter" />-->
      
      <!--Only log events at the specified range level are logged-->
      <filter type="log4net.Filter.LevelRangeFilter">    
        <param name="LevelMin" value="DEBUG" />    
        <param name="LevelMax" value="FATAL" />    
      </filter>
      
      <!--Log Output Format-->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%Time:%date thread ID: [%thread] Log level:%-5level Error class:%logger Error Description:%message %n" />
      </layout>
    </appender>

    <!--Output control level, from high to low: OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL -->
    <root>
      <priority value="ALL" />
      <level value="ALL" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>
</configuration>

2.3, Test Code

    class Program
    {
        //1,adopt NuGet install log4net Packages
        //2,Configuration file needs to be introduced
        //3,Read Configuration File from Code
        //4,adopt LogManager Obtain ILog Interface
        //5,Write different levels of logs
        static void Main(string[] args)
        {
            #region Log to file
            XmlConfigurator.Configure(new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "ConfigFile\\Log4NetToFile.config")));
            ILog logger = LogManager.GetLogger(typeof(Program));
            logger.Fatal("This is fatal message.");
            logger.Error("This is error message.");
            logger.Warn("This is warn message.");
            logger.Info("This is info message.");
            logger.Debug("This is debug message.");

            #region test maxSizeRollBackups and maximumFileSize
            //for (int i = 0; i < 1000000; i++)
            //{
            //    logger.Fatal($"No.{i + 1}Next Write Log");
            //}
            #endregion

            Console.Read();
            #endregion
        }
    }

2.4. Running results

Under the bin\Debug\Log folder, you can see the txt log file generated by date as follows:

Time: 2020-05-11 23:25:11,602 Thread ID: [1] Log level: FATAL error class: LinkTo.Test.ConsoleLog4Net.Program error description: This is fatal message. 
Time: 2020-05-11 23:25:11,616 Thread ID: [1] Log level: ERROR error class: LinkTo.Test.ConsoleLog4Net.Program error description: This is error message. 
Time: 2020-05-11 23:25:11,617 Thread ID: [1] Log level: WARN error class: LinkTo.Test.ConsoleLog4Net.Program error description: This is warn message. 
Time: 2020-05-11 23:25:11,618 Thread ID: [1] Log level: INFO error class: LinkTo.Test.ConsoleLog4Net.Program error description: This is info message. 
Time: 2020-05-11 23:25:11,618 Thread ID: [1] Log level: DEBUG error class: LinkTo.Test.ConsoleLog4Net.Program error description: This is debug message. 

Topics: C# encoding github xml