NUnit &测试log4net动态日志文件位置

发布于 2024-12-07 16:17:03 字数 3330 浏览 0 评论 0原文

我正在编写一个应用程序,用户可以在其中更改(在运行时)存储 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

韶华倾负 2024-12-14 16:17:03

我没有测试它,但我认为您需要在 MyMethod 中删除对 XmlConfigurator.Configure(); 的调用,因为这将覆盖您在测试类中所做的配置。

I did not test it but I think you need to remove the call to XmlConfigurator.Configure(); in MyMethod because this will overwrite the configuration you do in the test class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文