log4net tutorial log classification and automatic maintenance example

  • 2020-11-20 06:03:38
  • OfStack

If we need to configure different ILog, the process goes like this, first we create one ILoggerRepository, through which we do the logging level configuration, and various Appender, and then we get one Ilog object from ILoggerRepository through LogManager, then we can write the logging. The code is as follows:


public static ILog GetLogger(string repositoryName = "")
        {
            if (string.IsNullOrEmpty(repositoryName)) return LogManager.GetLogger("Defalut");
            ILoggerRepository repository = null;
            try
            {
                repository = LogManager.GetRepository(repositoryName);
            }
            catch (Exception) { }
            // Find direct return ilog
            if (repository != null)
                return LogManager.GetLogger(repositoryName, "Defalut");
            // If you don't find it, you create it. If you have multiple threads, it's possible to create it when it exists 
            try
            {
                repository = LogManager.CreateRepository(repositoryName);
            }
            catch (Exception)
            {
                repository = LogManager.GetRepository(repositoryName);
            }
            // Configure log levels    read Appsettings The default configuration   
            var appSet = ConfigurationManager.AppSettings.AllKeys;
            // Find log level 
            const string logLevel = "LogLevel";
            var hasSettings = Array.IndexOf(appSet, logLevel);
            if (hasSettings > -1)
            {
                var level = ConfigurationManager.AppSettings[logLevel].ToLower();
                if (level == "all") repository.Threshold = Level.All;
                else if (level == "debug") repository.Threshold = Level.Debug;
                else if (level == "info") repository.Threshold = Level.Info;
                else if (level == "warn") repository.Threshold = Level.Warn;
                else if (level == "error") repository.Threshold = Level.Error;
                else if (level == "fatal") repository.Threshold = Level.Fatal;
                else if (level == "off") repository.Threshold = Level.Off;
            }
            else repository.Threshold = Level.All;
            // To find the output Appender
            const string logAppender = "LogAppender";
            hasSettings = Array.IndexOf(appSet, logAppender);
            if (hasSettings > -1)
            {
                var appenders = ConfigurationManager.AppSettings[logAppender].ToLower().Split(',');
                foreach (var appender in appenders)
                {
                    if (appender == "rollingfile") LoadRollingFileAppender(repository);
                    else if (appender == "console") LoadConsoleAppender(repository);
                    else if(appender == "trace") LoadTraceAppender(repository);
                }
            }
            else LoadRollingFileAppender(repository);
            return LogManager.GetLogger(repositoryName, "Default");
        }

Log4net maintains ILog and ILoggerRepository automatically, so you don't need to save it, just get it through LogManger. But I didn't find a way to find out if the specified ILoggerRepository exists, so I checked with try catch in the above code. Since we configured log4net in code, but still wanted to configure log levels and output types, I chose to configure it in the Appsettings file, once for all ILoggerRepository. The reason for not configuring each function is mainly because of the configuration hassle, and if you do, it might be better to configure a different logger directly in log4net, referred to by loggername.

Log maintenance

So the next question is, how do you delete logs?

log4net Can be configured with RollingFileAppender, which translates to a scroll file. This can be done by setting two parameters, MaximumFileSize and MaxSizeRollBackups. Each time the log file reaches a certain size, a new file will be generated. The maximum total number of files is MaxSizeRollBackups, but only if the file name is 1.

For example, we adopt the following configuration:


<!--RollingFileAppender: Output to a file -->
    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender">
      <!-- Log path -->
      <file value="Logs/" />
      <!-- Overwrite or not, the default is append true-->
      <appendToFile value="true"/>
      <!-- Does not occupy the log file process -->
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <rollingStyle value="Composite"/>
      <!-- The file name -->
      <DatePattern value="yyyy-MM-dd HH' when .log'"></DatePattern>
      <!-- Set up unlimited backup =-1  , the maximum number of backups is 1000-->
      <param name="MaxSizeRollBackups" value="1000"/>
      <!-- The size of each file -->
      <param name="MaximumFileSize" value="500KB"/>
      <!-- Can the name be changed   for false Can be changed -->
      <param name="StaticLogFileName" value="false"/>
      <layout type="log4net.Layout.PatternLayout">
        <!-- The output format -->
        <conversionPattern value="%n [Record time] %date%n 【 description 】 %message%n"/>
      </layout>
    </appender>

The effect is that the log is in hours, with a maximum of 1000 backups per hour and a log file after every 500kb. As the number of days increases, the number of files starts to grow and we need to clean it up ourselves. So the above configuration can be changed slightly:


<!--RollingFileAppender: Output to a file -->
    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender">
      <!-- Log path -->
      <file value="Logs/ The log .log" />
      <!-- Overwrite or not, the default is append true-->
      <appendToFile value="true"/>
      <!-- Does not occupy the log file process -->
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <rollingStyle value="Composite"/>
      <!-- The file name -->
      <DatePattern value="yyyy-MM-dd HH' when .log'"></DatePattern>
      <!-- Set up unlimited backup =-1  , the maximum number of backups is 1000-->
      <param name="MaxSizeRollBackups" value="1000"/>
      <!-- The size of each file -->
      <param name="MaximumFileSize" value="500KB"/>
      <!-- Can the name be changed   for false Can be changed -->
      <param name="StaticLogFileName" value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <!-- The output format -->
        <conversionPattern value="%n [Record time] %date%n 【 description 】 %message%n"/>
      </layout>
    </appender>

Basically, the log file name is set, and is a static name, not allowed to change. This way, the maximum number of log files is 1000, no need to maintain manually, you will see such a log file name:

Log.log log.log.1 log.log.2... The default is that the last number of the file name is the oldest, so look at the new log, mainly in the first file name.
A word of caution: if Appender is set to use a static file name, the history log will be overwritten, and the history log is very concerned about the application, I suggest not to use this scheme, clean up the log, it is better to write code.


Related articles: