开发者

NUnit & testing log4net dynamic log file location

开发者 https://www.devze.com 2023-04-10 06:41 出处:网络
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.

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>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号