Log4Net : RollingFileAppender에 롤링 날짜로 최대 백업 파일 설정
다음 구성이 있지만 날짜 롤링 스타일에서 최대 백업 파일을 설정하는 방법에 대한 문서를 찾을 수 없습니다. 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>
당신은 할 수 없습니다.
에서 log4net SDK 참조
RollingFileAppender 클래스
주의
날짜 / 시간 경계에서 롤링 할 때 최대 백업 파일 수는 지원되지 않습니다.
지원되지는 않지만이 상황을 처리하는 방법은 다음과 같습니다.
이것은 내 구성입니다.
<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>
응용 프로그램 시작시 다음을 수행합니다.
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
}
Sub 메서드는 확장 메서드이며 기본적으로 다음과 같이 string.format을 래핑합니다.
/// <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);
}
}
I spent some time looking into this a few months ago. v1.2.10 doesn't support deleting older log files based on rolling 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 issue and the patch can be found at https://issues.apache.org/jira/browse/LOG4NET-27 .
To limit the number of logs, do not include the year or month in the datepattern,e.g. datePattern value="_dd'.log'"
This will create a new log each day, and it will get overwritten next month.
Not sure exactly what you need. Below is an extract 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".log""/>
<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>
I recently came across this need when attempting to clean up log logs based on a maxAgeInDays configuration value passed into my service... As many have before me, I became exposed to the NTFS 'feature' Tunneling, which makes using FileInfo.CreationDate problematic (though I have since worked around this as well)...
Since I had a pattern to go off of, I decided to just roll my own clean up method... My logger is configured programmatically, so I merely call the following after my logger setup has completed...
//.........................
//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);
}
}
}
Probably not the prettiest approach, but working pretty well for our purposes...
NLog, which is set up nearly the same way as Log4Net (& is actively maintained - even has support for .NET Core), supports rolling logs based on date.
It's fairly easy to inherit from a log4net appender and add say your own override method which performs the clean up of files. I overrode OpenFile to do this. Here's an example of a custom log4net appender to get you started: https://stackoverflow.com/a/2385874/74585
'Nice programing' 카테고리의 다른 글
| ASP.NET MVC 3과 4의 차이점은 무엇입니까? (0) | 2020.11.24 |
|---|---|
| Firebase 용 Cloud Functions-결제 계정이 구성되지 않음 (0) | 2020.11.24 |
| 엔트로피의 컴퓨터 과학 정의는 무엇입니까? (0) | 2020.11.24 |
| 회귀 모델에서 스크리닝 (다중) 공선 성 (0) | 2020.11.24 |
| 웹 서버로서의 Amazon EC2? (0) | 2020.11.24 |