如何在wpf应用程序的Config文件中将自定义属性添加到tracelistener

时间:2015-07-08 12:32:33

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

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

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

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

我认为解决方案是我们可以添加自定义配置部分,但想知道我们是否可以尝试使用更好的解决方案?

2 个答案:

答案 0 :(得分:3)

根据这篇文章,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" />

注意:

在完全构造侦听器实例之后 之后,才会从配置文件中填充Attributes集合。您需要确保在完全实例化侦听器对象之后,但在首次使用它之前调用它。

答案 1 :(得分:-1)

不可以更改架构,因此您必须添加自定义部分。 有很多文章解释了如何像这样做create a custom config section

相关问题