在运行时更改日志记录位置

本文关键字:记录 位置 日志 运行时 | 更新日期: 2023-09-27 17:50:11

是否有另一种方法来改变entlib的日志块的日志记录位置?目前我有以下代码来做更改

     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();

问题是,当用户没有写访问权限时,更改不会保存到日志文件

在运行时更改日志记录位置

您可以使用Using the Fluent Configuration 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