是否有其他方法可以更改entlib的Logging块的日志记录位置? 目前我有以下代码进行更改
var location = CommonConfiguration.ErrorLogPath;
ConfigurationFileMap configFileMap = new ConfigurationFileMap();
configFileMap.MachineConfigFilename = "AppName.exe.config";
var entLibConfig = ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
LoggingSettings loggingSettings = (LoggingSettings)entLibConfig.GetSection(LoggingSettings.SectionName);
RollingFlatFileTraceListenerData fileTraceListener = loggingSettings.TraceListeners.Get("Rolling Flat File Trace Listener") as RollingFlatFileTraceListenerData;
fileTraceListener.FileName = Path.Combine(location, @"Log\Appname.log");
entLibConfig.Save();
这个问题是,当用户没有写入权限时,更改不会保存到日志记录文件
答案 0 :(得分:2)
您可以使用Fluent配置API,例如以下单元测试代码:
[Test]
public void TestLoggingWithFluentConfigurationAPI()
{
var builder = new ConfigurationSourceBuilder();
builder.ConfigureLogging()
.WithOptions
.DoNotRevertImpersonation()
.LogToCategoryNamed("Basic")
.SendTo.FlatFile("Basic Log File")
.FormatWith(new FormatterBuilder()
.TextFormatterNamed("Text Formatter")
.UsingTemplate(
"Timestamp: {timestamp}{newline Message: {message}{newline}Category: {category}{newline}"))
.ToFile("d:\\logs\\BasicTest.log")
.SendTo.RollingFile("Rolling Log files")
.RollAfterSize(1024)
.ToFile("d:\\logs\\RollingTest.log")
.LogToCategoryNamed("General")
.WithOptions.SetAsDefaultCategory()
.SendTo.SharedListenerNamed("Basic Log File");
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current
= EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
LogWriterFactory logFactory = new LogWriterFactory(configSource);
LogWriter logWriter = logFactory.CreateDefault();
logWriter.Write("This is test message", "Basic");
logWriter.Write("This is default message");
string logfilepath = Path.Combine("d:", "logs\\BasicTest.log");
Assert.IsTrue(File.Exists(logfilepath));
Assert.IsTrue(File.Exists("d:\\logs\\RollingTest.log"));
}
参考: http://msdn.microsoft.com/en-us/library/ff664363(PandP.50).aspx