c# - 如何在 wpf 应用程序的配置文件中将自定义属性添加到 tracelistener

标签 c# .net wpf configuration-files tracelistener

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

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

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

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

最佳答案

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

它还引用了:

Classes that are derived from the TraceListener class can add custom attributes by overriding the GetSupportedAttributes method and returning a string array of custom attribute names.

通过关注 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 集合不会从配置文件中填充,直到之后您的监听器实例完全构建。您需要确保在您的监听器对象完全实例化之后但在首次使用之前调用它。

关于c# - 如何在 wpf 应用程序的配置文件中将自定义属性添加到 tracelistener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31292792/

相关文章:

c# - 基于标志的条件绑定(bind)

c# - C# .NET 4.5 TcpClient 类是用什么语言实现的?

.net - Entity Framework 4 保存并取消

c# - ObservableCollection.CollectionChanged 没有在 ToolBar 上选择正确的 DataTemplate

wpf - 如何撤消由绑定(bind)引起的 TextBox 的文本更改?

c# - 内存样本中的Naudio回放会产生声音的延迟和不美观的间隙

c# - 此 C 函数的正确 C# PInvoke 签名

c# - LINQ 到 XML : How to select the next element

.net - MSTest 失败并显示错误消息 'Results file does not exist. Publish failed'

c# - 将 PDF 嵌入到 WPF 应用程序中