企业库6-动态更改日志文件名 [英] Enterprise Library 6 - dynamically change log file name

查看:117
本文介绍了企业库6-动态更改日志文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在C#中动态设置日志文件夹和文件名,以覆盖日志记录配置的侦听器"部分中的配置值(文件名)?尝试遵循以下链接,但仅适用于EL 5将日志消息转到以前创建的日志文件

Is it possible to dynamically set log folder and file name in C# which overrides the config value(file name) in the Listeners section of logging configuration? Tried to follow the below link but it is applicable only for EL 5 Log messages going to previously created log file

这是我初始化EL记录的方式:

This is how i Initialize 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条目在listeners标记内:

These are my web.config entries inside the listeners tag:

 <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写入相应的跟踪和错误日志.

I use Logger.Write and ExceptionPolicy.HandleException to write to the corresponding trace and error logs.

推荐答案

最好的(也是最简单的!)方法是使用编程配置来设置文件名.

The best (and easiest!) approach would be to use programmatic configuration to set the filename.

但是,您可以使用类似的方法在运行时修改设置.在外部文件中设置配置,并使用app/web.config中的文件配置源.外部文件是必需的,以避免配置是只读异常.

However, you can use a similar approach to modify settings at runtime. Setup the configuration in an external file and use a file configuration source in app/web.config. An external file is necessary to avoid a configuration is read-only exception.

<?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):

And configure the external file (entlib.config in this case):

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

这篇关于企业库6-动态更改日志文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆