以编程方式定义log4net文件appender DatePattern属性
本文关键字:appender DatePattern 属性 文件 log4net 编程 方式 定义 | 更新日期: 2023-09-27 18:09:26
我尝试以编程方式实例化log4net滚动文件附加程序,如下所示:
private void GetFileAppender(string appenderName)
{
// Get the logger repository hierarchy.
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
/// Set the pattern layout for this appender
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
patternLayout.ActivateOptions();
/// Instantiate a new file appender
this._fileAppender = new RollingFileAppender();
this._fileAppender.Name = appenderName + "FileAppender";
this._fileAppender.AppendToFile = true;
this._fileAppender.Layout = patternLayout;
this._fileAppender.File = "C:''LogTest_";
this._fileAppender.StaticLogFileName = false;
this._fileAppender.DatePattern = "dd.MM.yyyy_hh'.log'";
this._fileAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
this._fileAppender.MaximumFileSize = "10MB";
this._fileAppender.MaxSizeRollBackups = 10;
/// Define filter for this appender
LevelRangeFilter levelRangeFilter = new LevelRangeFilter { LevelMin = Level.Debug, LevelMax = Level.Fatal, AcceptOnMatch = true };
DenyAllFilter denyAllFilter = new log4net.Filter.DenyAllFilter();
this._fileAppender.AddFilter(levelRangeFilter);
this._fileAppender.AddFilter(denyAllFilter);
this._fileAppender.ActivateOptions();
hierarchy.Root.AddAppender(this._fileAppender);
hierarchy.Root.Level = Level.Debug;
hierarchy.Configured = true;
}
日志记录本身工作正常。我唯一的问题是文件名的模式不起作用。我没有得到DatePattern属性定义的日志文件的DateTime模式和文件扩展名。我只是得到"LogTest_"作为文件名,没有日期时间和扩展名。
如何解决这个问题?如果我在我的App.config中通过XAML配置它,它就会分叉。但是我想用程序来解决这个问题。
解决:问题是我必须将滚动样式设置为Composite
this._fileAppender.RollingStyle = RollingFileAppender.RollingMode.Composite;
通过这样做,它采用属性DatePattern定义的模式
看这篇文章
在RollingFileAppender
中,您有DatePattern
属性:
RollingFileAppender roller = new RollingFileAppender();
roller.DatePattern = "yyyy.MM.dd";;