I am attempting to programmatically create a rolling file appender in C#. I'm using Visual Studios 2008. I am using log4net version 1.2.0.30714.

My main issue is that my rolling file appender is acting like a file appender. The log file will not roll based upon any size or date criteria I give it. Below is my configuration and I would appreciate any insight or suggestions. Below the code is some of the ideas I have tried.

string path = "Logs\";
string filename = "test.log";

if (!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}

log4net.Layout.PatternLayout patternLayout = new log4net.Layout.PatternLayout("[%d] %l %n   - %m %n%n");
patternLayout.ActivateOptions();

RollingFileAppender appender = new RollingFileAppender();
appender.Threshold = Level.ALL;
appender.StaticLogFileName = false;
appender.CountDirection = 0; // Makes the logs count 1, 2, 3
appender.RollingStyle = RollingFileAppender.RollingMode.Size;
appender.MaximumFileSize = "1KB";
appender.MaxFileSize = 1 * 1024; // 1 KB
appender.MaxSizeRollBackups = 5;
appender.DatePattern = "yy.MM.dd.hh.mm.ss";
appender.Layout = patternLayout;
appender.Name = "QTracImportHelper";
appender.ImmediateFlush = true;
appender.File = filename;
appender.Writer = new StreamWriter(path + filename, true);
appender.ActivateOptions();

Hierarchy hierarchy = (Hierarchy)LogManager.GetLoggerRepository();
hierarchy.Root.AddAppender(appender);
hierarchy.Configured = true;

I've noticed that removing the StreamWriter leads to no file being created at all but no exceptions. Removing the file name causes an exception from within log4net. I have tried using both MaxFileSize and MaximumFileSize to no avail as well as changing the rolling stile to Date and Composite. Additionally if the writer stream is malformed it will create the same exception as not including the File property ({"Value cannot be null.\r\nParameter name: fileName"}{System.ArgumentNullException}).

有帮助吗?

解决方案

I think this may be due to you supplying the "Writer" parameter directly before the ActivateOptions() call. The writer should be opened by the RollingLogFileAppender not externally. It's only exposed because of the inheritance of the class from TextWriterAppender.

//Don't do this:
//appender.Writer = new StreamWriter(path + filename, true);
//Do fully-qualify the file name:
appender.File = Path.Combine(path, filename);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top