0

Возможно ли динамически установить папку журнала и имя файла в C#, которая переопределяет значение конфигурации (имя файла) в разделе «Слушатели» конфигурации регистрации? Попробовал следовать ссылку ниже, но он применим только для EL 5 Log messages going to previously created log fileEnterprise Library 6 - динамически изменить имя файла журнала

Это, как я Инициализировать EL Logging:

IConfigurationSource configurationSource = ConfigurationSourceFactory.Create(); 
     LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource); 
     Logger.SetLogWriter(logWriterFactory.Create(), false); 

     ExceptionPolicyFactory factory = new ExceptionPolicyFactory(configurationSource); 
     ExceptionPolicy.SetExceptionManager(factory.CreateManager());   

Это мои записи web.config внутри тега слушателей:

<add name="RollingFlatFileTraceLog" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
    listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
    fileName="C:\logs\Trace.log" footer="" 
    formatter="CustomRollingFlatFileLogFormatter" 
    header="" rollFileExistsBehavior="Overwrite" rollInterval="Day" 
    rollSizeKB="2048" maxArchivedFiles="52" /> 
    <add name="RollingFlatFileErrorLog" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
    listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
    fileName="C:\logs\Error.log" footer="----------------------------------------" 
    formatter=" CustomRollingFlatFileLogFormatter " 
    header="----------------------------------------" rollFileExistsBehavior="Overwrite" 
    rollInterval="Day" rollSizeKB="2048" maxArchivedFiles="52" /> 

Я использую Logger.Write и ExceptionPolicy.HandleException для записи в соответствующие журналы трассировки и ошибок.

ответ

1

Лучший (и самый простой!) Подход - использовать программную конфигурацию для установки имени файла.

Однако вы можете использовать аналогичный подход для изменения настроек во время выполнения. Настройте конфигурацию во внешнем файле и используйте источник конфигурации файла в app/web.config. Внешний файл необходим, чтобы избежать конфигурации, это исключение только для чтения.

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <configSections> 
     <section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" /> 
    </configSections> 
    <enterpriseLibrary.ConfigurationSource selectedSource="File-based Configuration Source"> 
     <sources> 
      <add name="File-based Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
       filePath="entlib.config" /> 
     </sources> 
    </enterpriseLibrary.ConfigurationSource> 
    <startup> 
     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/> 
    </startup> 
</configuration> 

и настроить внешний файл (entlib.config в данном случае):

<configuration> 
    <configSections> 
     <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" /> 
     <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" /> 
    </configSections> 
    <exceptionHandling> 
     <exceptionPolicies> 
      <add name="Policy"> 
       <exceptionTypes> 
        <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
         postHandlingAction="NotifyRethrow"> 
         <exceptionHandlers> 
          <add name="Logging Exception Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
           logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling" 
           formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling" 
           priority="0" /> 
         </exceptionHandlers> 
        </add> 
       </exceptionTypes> 
      </add> 
     </exceptionPolicies> 
    </exceptionHandling> 
    <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General"> 
     <listeners> 
      <add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
       listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
       source="Enterprise Library Logging" formatter="Text Formatter" 
       log="" machineName="." traceOutputOptions="None" /> 
      <add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
       listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
       fileName="trace.log" /> 
     </listeners> 
     <formatters> 
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
       template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}" 
       name="Text Formatter" /> 
     </formatters> 
     <categorySources> 
      <add switchValue="All" name="General"> 
       <listeners> 
        <add name="Flat File Trace Listener" /> 
       </listeners> 
      </add> 
     </categorySources> 
     <specialSources> 
      <allEvents switchValue="All" name="All Events" /> 
      <notProcessed switchValue="All" name="Unprocessed Category" /> 
      <errors switchValue="All" name="Logging Errors &amp; Warnings"> 
       <listeners> 
        <add name="Event Log Listener" /> 
       </listeners> 
      </errors> 
     </specialSources> 
    </loggingConfiguration> 
</configuration> 

Используйте SerializableConfigurationSource из блоге:

public class SerializableConfigurationSource : IConfigurationSource 
{ 
    Dictionary<string, ConfigurationSection> sections = new Dictionary<string, ConfigurationSection>(); 

    public SerializableConfigurationSource() 
    { 
    } 

    public ConfigurationSection GetSection(string sectionName) 
    { 
     ConfigurationSection configSection; 

     if (sections.TryGetValue(sectionName, out configSection)) 
     { 
      SerializableConfigurationSection section = configSection as SerializableConfigurationSection; 

      if (section != null) 
      { 
       using (StringWriter xml = new StringWriter()) 
       using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(xml)) 
       { 
        section.WriteXml(xmlwriter); 
        xmlwriter.Flush(); 

        MethodInfo methodInfo = section.GetType().GetMethod("DeserializeSection", BindingFlags.NonPublic | BindingFlags.Instance); 
        methodInfo.Invoke(section, new object[] { XDocument.Parse(xml.ToString()).CreateReader() }); 

        return configSection; 
       } 
      } 
     } 

     return null; 
    } 

    public void Add(string sectionName, ConfigurationSection configurationSection) 
    { 
     sections[sectionName] = configurationSection; 
    } 

    public void AddSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler) 
    { 
     throw new NotImplementedException(); 
    } 

    public void Remove(string sectionName) 
    { 
     sections.Remove(sectionName); 
    } 

    public void RemoveSectionChangeHandler(string sectionName, ConfigurationChangedEventHandler handler) 
    { 
     throw new NotImplementedException(); 
    } 

    public event EventHandler<ConfigurationSourceChangedEventArgs> SourceChanged; 

    public void Dispose() 
    { 
    } 
} 

Bootstrap блоков при запуске:

IConfigurationSource configSource = ConfigurationSourceFactory.Create(); 

var loggingSettings = configSource.GetSection(LoggingSettings.SectionName) as LoggingSettings;  
var data = loggingSettings.TraceListeners.First(t => t.Name == "Flat File Trace Listener") as FlatFileTraceListenerData; 
// Change the file name 
data.FileName = "trace_1.txt"; 

var loggingXmlConfigSource = new SerializableConfigurationSource(); 
loggingXmlConfigSource.Add(LoggingSettings.SectionName, loggingSettings); 

var logFactory = new LogWriterFactory(loggingXmlConfigSource); 
Logger.SetLogWriter(logFactory.Create()); 

IConfigurationSource config = ConfigurationSourceFactory.Create(); 
ExceptionPolicyFactory factory = new ExceptionPolicyFactory(config); 

ExceptionManager exManager = factory.CreateManager(); 
ExceptionPolicy.SetExceptionManager(exManager); 

// This will log to the file trace_1.txt 
ExceptionPolicy.HandleException(new Exception(), "Policy"); 
+0

Thanks Randy, Changed to RollingFlatFileListenerData, смог использовать ваше решение, имя файла журнала динамически устанавливается в памяти во время запуска и работает как ожидается! Еще раз спасибо. Поскольку мое решение работает в службе Windows (которая работает без каких-либо перезапусков), чтобы обновить память, угадайте, что мне нужно перезапустить службу в полночь, чтобы повторная инициализация журнала (мое требование - поместить файл журнала в каталог с сегодняшним именем YYYYMMDD - 12.AM). – appootan

0

Как вы уже упоминали в сообщении, установите конфигурацию во внешний файл. Внешний файл означает, вы можете подтвердить, в каком пути мы должны поместить файл Entlib.config.

+0

Что-то вроде этого -> https://stackoverflow.com/questions/10300063/can-i-create-config-file-and-include-it-to-web-config – appootan