1

我正在尝试构建一个使用 Enterprise Library 5.0 日志记录代码块的日志库,并且我已经能够创建一个 CustomTraceListener,当配置来自配置文件但我尝试通过配置源生成器配置它时我得到以下错误:

"Unable to find appropriate 0 argument constructor for CustomTraceListener"

当我尝试使用 EL5.0 代码库查找错误时,特别是在构建 CustomTraceListenerData 的构造字符串时遇到了问题。

这是代码:

using System;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;

namespace AHCALoggerLibrary
{
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class ServiceTraceListener : CustomTraceListener
{
    public ServiceTraceListener()
        : base() {}

    public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, object data)
    {
        base.TraceData(eventCache, source, eventType, id, data);
    }

    public override void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, params object[] data)
    {
        base.TraceData(eventCache, source, eventType, id, data);
    }

    public override void Write(string message)
    {
        throw new NotImplementedException();
    }

    public override void WriteLine(string message)
    {
        throw new NotImplementedException();
    }
}

public class AHCALogger
{
    private static AHCALogger _logger = new AHCALogger();

    private LogWriter _Service = null; 

    public static LogWriter Service { get { return _logger._Service;} }

    private AHCALogger() { }

    public static void Init()
    {
        var builder = new ConfigurationSourceBuilder();

        builder.ConfigureLogging()
               .WithOptions
                 .DoNotRevertImpersonation()
               .LogToCategoryNamed("General")
                .WithOptions.SetAsDefaultCategory()
                    .SendTo.Custom<CustomTraceListener>("ServiceTraceListener")
                   .FormatWith(new FormatterBuilder()
                     .TextFormatterNamed("Text Formatter")
                       .UsingTemplate("Timestamp: {timestamp}...{newline})}"))
                 .SendTo.EventLog("Formatted EventLog TraceListener")
                    .FormatWithSharedFormatter("Text Formatter")
                      .ToLog("Application");

        var configSource = new DictionaryConfigurationSource();
        builder.UpdateConfigurationWithReplace(configSource);
        EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
        _logger._Service = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
    }
}
}

然后使用记录器:

        AHCALogger.Init();
        AHCALogger.Service.Write("hello");

我怀疑我配置错误,因为当我使用配置文件设置并调用时它确实有效:

LogWriter ahcaLogger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
ahcaLogger.Write("hello");

我试图找到有关如何使用 ConfigurationSourceBuilder 的更多信息,但无济于事。

谁能帮我这个?

4

1 回答 1

1

你需要更换

.SendTo.Custom<CustomTraceListener>("ServiceTraceListener") 

 .SendTo.Custom<ServiceTraceListener>("ServiceTraceListener")

错误消息基本上告诉您不能实例化抽象类。您需要传入具体类。无论如何,您都不需要 [ConfigurationElementType(typeof(CustomTraceListenerData))],因为它没有效果。

要将自定义配置数据传递给您的跟踪侦听器,您需要注意数据存储在 TraceListener 基类的 Attributes 集合中。这意味着您不能在 ctor 中初始化您的侦听器,而是在第一次日志调用时。

我已经清理了您的静态记录器内容以使其更容易。

我在调试这个烦人的SynchronizationLockException时注意到

“对象同步方法是从未同步的代码块中调用的。”

这似乎是Entlib5 yuck中的一个错误。除了自己重新编译统一并修复它之外,我还没有找到解决这个问题的方法。

这是带有自定义数据的工作记录器的代码。

using System;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using System.Linq;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;

class Program
{
    static void Main(string[] args)
    {
        AHCALogger.Service.Write(new LogEntry() { Message = "Hi" });
    }
}

public static class AHCALogger
{
    static Lazy<LogWriter> _Service = new Lazy<LogWriter>(Init);
    public static LogWriter Service
    {
        get { return _Service.Value; }
    }

    static LogWriter Init()
    {
        var builder = new ConfigurationSourceBuilder();
        var serviceConfig = new NameValueCollection();
        serviceConfig.Add("Key", "data");
        builder.ConfigureLogging()
            .LogToCategoryNamed("General")
            .WithOptions.SetAsDefaultCategory()
            .SendTo.Custom<ServiceTraceListener>("ServiceTraceListener", serviceConfig);

        var configSource = new DictionaryConfigurationSource();
        configSource.Add(LoggingSettings.SectionName, builder.Get(LoggingSettings.SectionName));
        var cont = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
        return cont.GetInstance<LogWriter>();
    }
}

public class ServiceTraceListener : CustomTraceListener
{
    public ServiceTraceListener() { }
    public override void Write(string message)
    {
        Console.WriteLine("Custom trace Listener Data {0}", 
            String.Join(Environment.NewLine, base.Attributes.Keys.OfType<string>().Select(key => "[" + key + "]: " + base.Attributes[key])));
        Console.WriteLine("message: {0}", message);
    }
    public override void WriteLine(string message) 
    {
        Write(message + Environment.NewLine);
    }
}
于 2012-05-05T08:39:55.827 回答