【问题标题】:How to add custom attribute to a tracelistener in Config file in wpf application如何在 wpf 应用程序的配置文件中将自定义属性添加到跟踪侦听器
【发布时间】:2015-09-26 08:54:07
【问题描述】:

我有以下日志文​​件 tracelistener,它扩展了 filelogtracelistener,它工作正常,我能够记录消息,但我想在其中指定一个额外的自定义属性,例如MaxUsers 及以下是它的外观。

 <add name="myFileListener" 
      type="MyCustomFileLogTraceListener, Microsoft.MyTools.Connections" 
      BaseFileName="IncidentTracking"
      Location="LocalUserDirectory" MaxUsers="500" />

目前此属性是自定义的,因此配置文件会出错。如何添加这样的自定义属性并在我的代码中使用它?

我认为作为一种解决方案,我们可以添加一个自定义配置部分,但想知道我们是否可以开箱即用地尝试一些更好的解决方案?

【问题讨论】:

  • 可以为您的跟踪侦听器添加自定义属性。查看我的答案以了解如何操作。

标签: c# .net wpf configuration-files tracelistener


【解决方案1】:

根据本文,TraceListener.Attributes Property 获取应用程序配置文件中定义的自定义跟踪侦听器属性。

它还引用了:

TraceListener 类派生的类可以添加自定义 通过覆盖 GetSupportedAttributes 方法和 返回自定义属性名称的字符串数组。

我能够通过像这样关注this example 来实现您想要的

string[] _supportedAttributes = new string[] { "MaxUsers", "maxusers", "maxUsers" };

/// <summary>
/// Allowed attributes for this trace listener.
/// </summary>
protected override string[] GetSupportedAttributes() {
    return _supportedAttributes;
}

/// <summary>
/// Get the value of Max Users Attribute 
/// </summary>
public int MaxUsers {
    get {
        var maxUsers = -1; // You can set a default if you want
        var key = Attributes.Keys.Cast<string>().
            FirstOrDefault(s => string.Equals(s, "maxusers", StringComparison.InvariantCultureIgnoreCase));
        if (!string.IsNullOrWhiteSpace(key)) {
            int.TryParse(Attributes[key], out maxUsers);
        }
        return maxUsers;
    }
}

这将允许我向配置文件添加自定义属性,看起来像

<add name="myFileListener" type="MyCustomFileLogTraceListener, Microsoft.MyTools.Connections" 
      BaseFileName="IncidentTracking"
      Location="LocalUserDirectory" MaxUsers="500" />

注意:

直到你的监听器实例完全构建之后,属性集合才会从配置文件中填充。您需要确保在完全实例化您的侦听器对象之后、但在首次使用之前调用它。

【讨论】:

    【解决方案2】:

    不,无法更改架构,因此您必须添加自定义部分。 有很多文章解释了它是如何做到的 create a custom config section

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 2016-05-12
      • 2010-11-26
      • 2010-10-06
      相关资源
      最近更新 更多