我尝试以编程方式实例化log4net rollingfile appender:
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_”作为文件名而没有dateTime和扩展名。
如何解决这个问题?如果我在App.config中通过XAML配置它,它会分叉。但我想以编程方式解决这个问题。
解决: 问题是我必须将RollingStyle设置为 Composite
this._fileAppender.RollingStyle = RollingFileAppender.RollingMode.Composite;
通过这样做,它需要由属性DatePattern定义的模式。
答案 0 :(得分:0)
请参阅this post。
在RollingFileAppender
中,您拥有DatePattern
属性:
RollingFileAppender roller = new RollingFileAppender();
roller.DatePattern = "yyyy.MM.dd";;