开发者

EntLib 5 Changing logging location at runtime

Is there another way to change the logging location of Logging block of entlib? Currently i have the following code to do the change

开发者_运维知识库     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();

the issue with this is that when users don't have write access the change isn't being saved to the logging file


You may use Using the Fluent Configuration API,like following unit test code:

     [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"));

     }

Reference: http://msdn.microsoft.com/en-us/library/ff664363(PandP.50).aspx

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜