Log4Net: set maximum backup files to RollingFileAppender with rolling date

I have the following configuration, but I can not find the documentation on how to set the maximum backup files in the style of the date calendar. I know that you can do this using the size promotion style using maxSizeRollBackups.

<appender name="AppLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="mylog.log" /> <appendToFile value="true" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <rollingStyle value="Date" /> <datePattern value=".yyMMdd.'log'" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d %-5p %c - %m%n" /> </layout> </appender> 
+55
log4net
Sep 18 '08 at 18:24
source share
8 answers

You can not.

from log4net SDK Reference
RollingFileAppender Class

Attention

The maximum number of backup files when dragging along date / time boundaries is not supported.

+40
Sep 18 '08 at 22:26
source share

Even if it is not supported, here is how I dealt with this situation:

This is my configuration:

  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="C:\logs\LoggingTest\logfile.txt" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <datePattern value="yyyyMMdd" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date - %message%newline" /> </layout> </appender> 

When starting the application, I:

  XmlConfigurator.Configure(); var date = DateTime.Now.AddDays(-10); var task = new LogFileCleanupTask(); task.CleanUp(date); 



 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using log4net; using log4net.Appender; using log4net.Config; public class LogFileCleanupTask { #region - Constructor - public LogFileCleanupTask() { } #endregion #region - Methods - /// <summary> /// Cleans up. Auto configures the cleanup based on the log4net configuration /// </summary> /// <param name="date">Anything prior will not be kept.</param> public void CleanUp(DateTime date) { string directory = string.Empty; string filePrefix = string.Empty; var repo = LogManager.GetAllRepositories().FirstOrDefault(); ; if (repo == null) throw new NotSupportedException("Log4Net has not been configured yet."); var app = repo.GetAppenders().Where(x => x.GetType() == typeof(RollingFileAppender)).FirstOrDefault(); if (app != null) { var appender = app as RollingFileAppender; directory = Path.GetDirectoryName(appender.File); filePrefix = Path.GetFileName(appender.File); CleanUp(directory, filePrefix, date); } } /// <summary> /// Cleans up. /// </summary> /// <param name="logDirectory">The log directory.</param> /// <param name="logPrefix">The log prefix. Example: logfile dont include the file extension.</param> /// <param name="date">Anything prior will not be kept.</param> public void CleanUp(string logDirectory, string logPrefix, DateTime date) { if (string.IsNullOrEmpty(logDirectory)) throw new ArgumentException("logDirectory is missing"); if (string.IsNullOrEmpty(logPrefix)) throw new ArgumentException("logPrefix is missing"); var dirInfo = new DirectoryInfo(logDirectory); if (!dirInfo.Exists) return; var fileInfos = dirInfo.GetFiles("{0}*.*".Sub(logPrefix)); if (fileInfos.Length == 0) return; foreach (var info in fileInfos) { if (info.CreationTime < date) { info.Delete(); } } } #endregion } 

The Sub method is an extension method, it basically wraps string.format as follows:

 /// <summary> /// Extension helper methods for strings /// </summary> [DebuggerStepThrough, DebuggerNonUserCode] public static class StringExtensions { /// <summary> /// Formats a string using the <paramref name="format"/> and <paramref name="args"/>. /// </summary> /// <param name="format">The format.</param> /// <param name="args">The args.</param> /// <returns>A string with the format placeholders replaced by the args.</returns> public static string Sub(this string format, params object[] args) { return string.Format(format, args); } } 
+34
May 26 '10 at 20:40
source share

I spent some time studying this a few months ago. v1.2.10 does not support the removal of older calendar-based log files by date. It is on the task list for the next release. I took the source code and added the functionality myself, and posted it for others if they are interested. The problem and patch can be found at https://issues.apache.org/jira/browse/LOG4NET-27 .

+11
Mar 12 '10 at 17:40
source share

To limit the number of magazines, do not indicate the year or month in the passport date, for example. datePattern value = "_dd'.log"

This will create a new journal every day, and it will be rewritten next month.

+6
Jun 07 '16 at 12:19
source share

Not sure what you need. The following is an excerpt from one of my lo4net.config files:

  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> <param name="File" value="App_Data\log"/> <param name="DatePattern" value=".yyyy-MM-dd-tt&quot;.log&quot;"/> <param name="AppendToFile" value="true"/> <param name="RollingStyle" value="Date"/> <param name="StaticLogFileName" value="false"/> <param name="maxSizeRollBackups" value="60" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%r %d [%t] %-5p %c - %m%n"/> </layout> </appender> 
+4
Sep 18 '08 at 18:32
source share

I recently encountered this need when trying to clear logs based on the maxAgeInDays configuration value passed to my service ... Like many of them, I became aware of the NTFS Tunneling function that uses FileInfo.CreationDate is problematic (although I have since also worked on this) ...

Since I had a template to leave, I decided to just minimize my own cleaning method ... My logger is configured programmatically, so I just call the following after completing the setup of my logger ...

  //......................... //Log Config Stuff Above... log4net.Config.BasicConfigurator.Configure(fileAppender); if(logConfig.DaysToKeep > 0) CleanupLogs(logConfig.LogFilePath, logConfig.DaysToKeep); } static void CleanupLogs(string logPath, int maxAgeInDays) { if (File.Exists(logPath)) { var datePattern = "yyyy.MM.dd"; List<string> logPatternsToKeep = new List<string>(); for (var i = 0; i <= maxAgeInDays; i++) { logPatternsToKeep.Add(DateTime.Now.AddDays(-i).ToString(datePattern)); } FileInfo fi = new FileInfo(logPath); var logFiles = fi.Directory.GetFiles(fi.Name + "*") .Where(x => logPatternsToKeep.All(y => !x.Name.Contains(y) && x.Name != fi.Name)); foreach (var log in logFiles) { if (File.Exists(log.FullName)) File.Delete(log.FullName); } } } 

This is probably not the most beautiful approach, but it works very well for our purposes ...

+1
Mar 12 '13 at 15:09
source share

NLog , which is configured in much the same way as Log4Net (actively supported, even supports .NET. Core), supports date-based sliding logs.

+1
Jan 09 '17 at 21:22
source share

It is fairly easy to inherit from a log4net application and add your own override method, which performs file cleanup. I redid OpenFile to do this. Here is an example of a custom log4net application to get you started: https://stackoverflow.com/a/464829/

0
Sep 27 '12 at 2:35
source share



All Articles