如何以编程方式更改文件位置?

我是Log4net的新手。

我设法通过添加配置文件和简单的日志记录来解决问题。

我已经将值硬编码为,"C:\temp\log.txt"但这还不够好。


慕标琳琳
浏览 375回答 3
3回答

BIG阳

log4net可以为您解决这个问题。在这种情况下,可以使用log4net.Util.PatternString选项处理程序格式化字符串类型的任何appender属性。PatternString甚至支持SpecialFolder枚举,该枚举启用以下优雅的配置:<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >&nbsp; &nbsp; <file type="log4net.Util.PatternString"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; value="%envFolderPath{CommonApplicationData}\\test.txt" />&nbsp; &nbsp; ...</appender>这是证明布丁的单元测试:[Test]public void Load(){&nbsp; &nbsp; XmlConfigurator.Configure();&nbsp; &nbsp; var fileAppender = LogManager.GetRepository()&nbsp; &nbsp; &nbsp; &nbsp; .GetAppenders().First(appender => appender is RollingFileAppender);&nbsp; &nbsp; var expectedFile =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Path.Combine(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Environment.GetFolderPath(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Environment.SpecialFolder.CommonApplicationData),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "test.txt");&nbsp; &nbsp; Assert.That(fileAppender,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Is.Not.Null & Has.Property("File").EqualTo(expectedFile));}以下测试验证log4net实际上已写入磁盘(这基本上使该测试成为“集成”测试,而不是单元测试,但我们暂时将其保留):[Test]public void Log4net_WritesToDisk(){&nbsp; &nbsp; var expectedFile =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Path.Combine(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Environment.GetFolderPath(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Environment.SpecialFolder.CommonApplicationData),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "test.txt");&nbsp; &nbsp; if (File.Exists(expectedFile))&nbsp; &nbsp; &nbsp; &nbsp; File.Delete(expectedFile);&nbsp; &nbsp; XmlConfigurator.Configure();&nbsp; &nbsp; var log = LogManager.GetLogger(typeof (ConfigTest));&nbsp; &nbsp; log.Info("Message from test");&nbsp; &nbsp; LogManager.Shutdown();&nbsp; &nbsp; Assert.That(File.ReadAllText(expectedFile),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Text.Contains("Message from test"));}注意:我强烈建议使用上面示例中演示的紧凑属性语法。删除所有这些“ <property name =”可以使您的配置更具可读性。
打开App,查看更多内容
随时随地看视频慕课网APP