NUnit &测试log4net动态日志文件位置
我正在编写一个应用程序,用户可以在其中更改(在运行时)存储 log4net 日志的目录。目录字符串存储在app.config中。
当我想使用 NUnit 测试日志文件是否在正确的目录中创建时,未创建日志文件(以及相应的目录)。
当在线查找这个问题时,我读到 NUnit 停止了日志记录工作,因为它本身使用了 log4net。提供的示例告诉您创建一个附加的 .config (Test.config),其中还包含 log4net 部分并在测试类中加载配置,我就是这么做的。
使用单元测试时仍然没有创建日志文件。
启动应用程序时,将按其应有的方式创建日志文件。
设置日志目录的方法:
public void MyMethod()
{
string logDirectory = app.Settings["LogDirectory"].Value;
//assure that the file name can be appended to the path
if (!logDirectory.EndsWith(@"\"))
{
logDirectory += @"\";
}
//find the rolling file appender and set its file name
XmlConfigurator.Configure();
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
foreach (IAppender appender in hierarchy.Root.Appenders)
{
if (appender is RollingFileAppender)
{
RollingFileAppender fileAppender = (RollingFileAppender)appender;
string logFileLocation = string.Format("{0}Estimation_Protocol_{1}.txt",
logDirectory, EstimatorHelper.SoftwareVersionAndDateTime());
fileAppender.File = logFileLocation;
fileAppender.ActivateOptions();
break;
}
}
log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Debug("Logging directory & file name set.");
}
测试类:
class EstimatorTests
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public EstimatorTests()
{
FileInfo fileInfo = new FileInfo(@"%property{LogName}");
log4net.Config.XmlConfigurator.Configure(fileInfo);
}
[Test]
public void TestLoadInputPaths()
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
string time = DateTime.Now.Ticks.ToString();
app.Settings["ProcessingProtocolDirectory"].Value = "C:\\thisFolderDoesntExist" + time;
Form mainForm = new Form();
Form.MyMethod();
Assert.IsTrue(Directory.Exists("C:\\thisFolderDoesntExist" + time));
//this assert fails!
}
}
log4net config:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%property{LogName}" />
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="5"/>
<maximumFileSize value="10MB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline%exception%newline"/>
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingFileAppender"/>
</root>
</log4net>
I'm writing an application where the user can change (at runtime) the directory where the log4net log is stored. The directory string is stored in the app.config.
When I want to test if the log file is created in the right directory with NUnit, the logfile (and the corresponding directory) is not created.
When looking online for this problem I read that NUnit stops the logging from working because it uses log4net itself. The provided sample tells you to create a additional .config (Test.config) which also contains the log4net sections and to load the configuration inside the testing class, which I did.
There is still no log file created when using the unit test.
When starting the application, the log file is created as it should.
Method to set the log directory:
public void MyMethod()
{
string logDirectory = app.Settings["LogDirectory"].Value;
//assure that the file name can be appended to the path
if (!logDirectory.EndsWith(@"\"))
{
logDirectory += @"\";
}
//find the rolling file appender and set its file name
XmlConfigurator.Configure();
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
foreach (IAppender appender in hierarchy.Root.Appenders)
{
if (appender is RollingFileAppender)
{
RollingFileAppender fileAppender = (RollingFileAppender)appender;
string logFileLocation = string.Format("{0}Estimation_Protocol_{1}.txt",
logDirectory, EstimatorHelper.SoftwareVersionAndDateTime());
fileAppender.File = logFileLocation;
fileAppender.ActivateOptions();
break;
}
}
log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Debug("Logging directory & file name set.");
}
The test class:
class EstimatorTests
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public EstimatorTests()
{
FileInfo fileInfo = new FileInfo(@"%property{LogName}");
log4net.Config.XmlConfigurator.Configure(fileInfo);
}
[Test]
public void TestLoadInputPaths()
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
string time = DateTime.Now.Ticks.ToString();
app.Settings["ProcessingProtocolDirectory"].Value = "C:\\thisFolderDoesntExist" + time;
Form mainForm = new Form();
Form.MyMethod();
Assert.IsTrue(Directory.Exists("C:\\thisFolderDoesntExist" + time));
//this assert fails!
}
}
The log4net config:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%property{LogName}" />
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="5"/>
<maximumFileSize value="10MB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline%exception%newline"/>
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingFileAppender"/>
</root>
</log4net>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我没有测试它,但我认为您需要在
MyMethod
中删除对XmlConfigurator.Configure();
的调用,因为这将覆盖您在测试类中所做的配置。I did not test it but I think you need to remove the call to
XmlConfigurator.Configure();
inMyMethod
because this will overwrite the configuration you do in the test class.