以编程方式访问Enterprise Library Logging配置(对象模型)?

时间:2010-08-14 22:46:36

标签: c# .net logging enterprise-library

我正在使用Enterprise Library 3.1,并希望以编程方式访问Logging Block(运行时,对象模型),特别是其跟踪侦听器和源。

例如,我想访问跟踪侦听器对象的Filename属性,以便知道日志文件在磁盘上的位置。

更新:查找使用运行时对象模型的答案,而不是解析XML配置。

4 个答案:

答案 0 :(得分:2)

您可以使用对象模型(用于配置)以编程方式访问日志记录配置。

要获取跟踪侦听器的特定数据,您应该查看TraceListenerData(以及特定的子类)。

此示例显示如何读取配置,然后获取TraceListeners:

// Open config file
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = @"MyApp.exe.config";

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

// Get EL log settings
LoggingSettings log = config.GetSection("loggingConfiguration") as LoggingSettings;

// Get TraceListener info
foreach(TraceListenerData listener in log.TraceListeners)
{
    // Check for listener types you care about
    if (listener is RollingFlatFileTraceListenerData)
    {
        RollingFlatFileTraceListenerData data = listener as RollingFlatFileTraceListenerData;
        Console.WriteLine(string.Format("Found RollingFlatFileLIstener with Name={0}, FileName={1}, Header={2}, Footer={3}, RollSizeKB={4}, TimeStampPattern={5},RollFileExistsBehavior={6}, RollInterval={7}, TraceOutputOptions={8}, Formatter={9}, Filter={10}",
            data.Name, data.FileName, data.Header, data.Footer, data.RollSizeKB, 
            data.TimeStampPattern, data.RollFileExistsBehavior, data.RollInterval,
            data.TraceOutputOptions, data.Formatter, data.Filter);
    }
    else // other trace listener types e.g. FlatFileTraceListenerData 
    {
    }
}

答案 1 :(得分:0)

显然,某些所需信息是私有地封装在企业库 Logger.Writer 实例(类型为{strong}上的LogWriterStructureHolder实例(其字段名为 structureHolder )中LogWriter)。
所以我实际上在寻找:Logger.Writer.structureHolder(但该字段是私有的)。

我用反射把它拉出来......

这些是重要的命名空间:

using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Logging;

这是反射代码,用于提取所需的私有数据:

// Get the private field.
FieldInfo fiLogStructHolder 
    = typeof(LogWriter).GetField("structureHolder", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);

// Obtain field value to get the private data.
LogWriterStructureHolder structureHolder 
    = (LogWriterStructureHolder)fiLogStructHolder.GetValue(Logger.Writer);

// Access the value's .TraceSources property of Type Dictionary<string, LogSource>.
// The string is the name of the category from configuration. 
int numSources = structureHolder.TraceSources.Count;

// Furthermore, access the listeners of any logging source by specifying:
int numListeners = structureHolder.TraceSources[0].Listeners.Count
                                             // ^-- Note: Picked first source for example.

如果有人可以找到相同数据的非私人入口点,请将其发布到答案中。感谢。

.NET Reflector致敬,以便为此答案提供便利。

答案 2 :(得分:0)

public static EmailTraceListenerData GetEmailLogConfiguration()
{
    var rootWebConfig1 = WebConfigurationManager.OpenWebConfiguration("/");
    var section = rootWebConfig1.GetSection("loggingConfiguration");
    var loggingSection = section as Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings;

    if (loggingSection != null) {
        // Reference to Microsoft.Practices.EnterpriseLibrary.Logging.dll and
        // Microsoft.Practices.EnterpriseLibrary.Common.dll required for the code below
        foreach (Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.TraceListenerData listener in loggingSection.TraceListeners) {
            var emailTraceListenerData = listener as EmailTraceListenerData;
            if (emailTraceListenerData != null) {
                // Can obtain FromAddress, ToAddress, SmtpServer and SmtpPort 
                // as property of  emailTraceListenerData;
                return emailTraceListenerData;
            }
        }
    }
    return null;
}

Web.config文件如下:

web.config file

对于Windows应用程序,您可以使用System.Configuration.ConfigurationManager.OpenExeConfiguration而不是WebConfigurationManager打开.config文件。

答案 3 :(得分:0)

其他答案似乎非常冗长,这是我的解决方案:

    public static TraceListenerData GetTraceListener(string name)
    {
        var log = ConfigurationManager.GetSection("loggingConfiguration") as LoggingSettings;

        return log.TraceListeners.Single(tl => tl.Name == name);
    }

一旦调用了这个帮助器方法,就可以将结果转换为侦听器所属的任何类型,例如RollingFlatFileTraceListenerData,EmailTraceListenerData,FormattedEventLogTraceListenerData,FormattedDatabaseTraceListenerData