我有以下日志文件 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/