hel*_*hab 9 c# logging log4net
我想以这样的方式配置log4net,即所有前一天的日志都应该自动存档.是否有可能在Log4Net中自动存档以前的日志.我想使用配置而不使用任何第三方库(如sharplibzip)编写任何代码来创建存档.
通过归档添加的另一件事是指压缩zip/rar格式的文件以节省磁盘空间.
抱歉,没有编写代码就无法归档文件.但是代码不会很复杂.
您可以创建继承自的自定义appender RollingFileAppender,并覆盖该AdjustFileBeforeAppend方法,以便向滚动文件添加行为.以下是滚动文件的现有方法,RollingFileAppender您可以覆盖该文件以添加存档.
使用该File属性查找文件名进程
// log4net.Appender.RollingFileAppender
protected virtual void AdjustFileBeforeAppend()
{
var fileToZip = File; // save the current file
if (this.m_rollDate)
{
DateTime now = this.m_dateTime.Now;
if (now >= this.m_nextCheck)
{
this.m_now = now;
this.m_nextCheck = this.NextCheckDate(this.m_now, this.m_rollPoint);
this.RollOverTime(true);
// zip the file if roll occurs here
}
}
if (this.m_rollSize)
{
if (this.File != null && ((CountingQuietTextWriter)base.QuietWriter).Count >= this.m_maxFileSize)
{
this.RollOverSize();
// zip the file if roll occurs here
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者你可以找到一个现有的appender来做你想要的,但我不知道.
我冒昧地将@stuartd的评论提升到答案,因为他提出的建议非常优雅.你可以简单地AdjustFileBeforeAppend以这种方式覆盖:
protected override void AdjustFileBeforeAppend() {
var previousFile = File;
base.AdjustFileBeforeAppend();
if (File != previousFile) { // zip the file }
}
Run Code Online (Sandbox Code Playgroud)
这是一种非常简洁的方式,但您可能希望能够区分两种卷(即日期和大小).例如,仅在日期滚动上进行压缩,以便将日期范围的文件保持在一起.
log4net 不包含任何压缩日志文件的功能。然而,压缩是在 .Net 框架中进行的(自 4.5 起),或者您可以使用Windows Shell API来压缩文件,因此您将拥有定期获取所有非当前日志文件的日志文件并将其压缩的代码:
-- assuming you don't have more that one appender
appender = LogManager.GetRepository().GetAppenders()
.OfType<RollingFileAppender>().FirstOrDefault();
if (appender == null) return; // no appenders found
var currentFile = appender.File;
-- dropping to pseudocode:
var files = Get_all_files_in_log_directory_which_match_log_file_pattern
but_aren't_the_current_file(current file);
if (ZipFiles(files...))
(DeleteFiles(files); // presumably
Run Code Online (Sandbox Code Playgroud)