Enterprise Library 6 - динамическое изменение имени файла журнала

Можно ли динамически установить папку журнала и имя файла в C #, которое переопределяет значение конфигурации (имя файла) в разделе Listeners конфигурации ведения журнала? Пытался перейти по ссылке ниже, но она применима только для EL 5 Сообщения журнала переход к ранее созданному файлу журнала

Вот как я инициализирую ведение журнала EL:

 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 внутри тега listeners:

 <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 для записи в соответствующие журналы трассировки и ошибок.


person appootan    schedule 11.06.2015    source источник


Ответы (2)


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

Однако вы можете использовать аналогичный подход для изменения настроек во время выполнения. Настройте конфигурацию во внешнем файле и используйте источник конфигурации файла в 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()
    {
    }
}

Загрузите блоки при запуске:

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");
person Randy supports Monica    schedule 24.07.2015
comment
Спасибо, Рэнди, измененный на RollingFlatFileListenerData, смог использовать ваше решение, имя файла журнала динамически устанавливается в памяти во время запуска и работает, как ожидалось !! Еще раз спасибо. Поскольку мое решение работает в службе Windows (которая работает без перезапуска), чтобы обновить память, думаю, мне нужно перезапустить службу в полночь для повторной инициализации ведения журнала (Мое требование - поместить файл журнала в каталог с сегодняшним названием ГГГГММДД - 12.AM). - person appootan; 24.07.2015

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

person Anush    schedule 02.11.2017
comment
Примерно так - ›stackoverflow.com/questions/10300063/ - person appootan; 16.11.2017