我最近阅读了Chris Love关于使用WCF跟踪来帮助进行故障排除的建议.
他通过在app.config文件中添加新的XML部分来启用跟踪,此后我在相同的技术中看到了类似的建议.
但是我们真的不想发送多个app.config文件.
我们绝对不希望客户在生产系统上修改它们!
有没有办法可以在app.config中设置WCF跟踪的各种设置,但是从代码打开/关闭跟踪?
理想情况下,我希望我的应用程序检查注册表,并仅在存在特定值时激活跟踪.
mth*_*rba 11
我的建议是使用一个自定义TraceFilter,它应用于附加到WCF TraceSources的所有侦听器(即"System.ServiceModel","System.ServiceModel.MessageLogging").在TraceFilter的ShouldTrace()方法中,您可以根据应用程序可用的任何信息有条件地禁止跟踪.
以下是一些示例代码,您可以将其作为起点.有一个静态助手类,它在应用程序的生命周期内全局和一次确定是应该启用还是禁用跟踪:
namespace WCF.Diagnostics
{
using System.Diagnostics;
public static class WcfDiagnosticsHelper
{
private readonly static bool _shouldTraceWcf;
static WcfDiagnosticsHelper()
{
// here, determine if WCF Tracing should be enabled or not
// i.e., read some custom settings from App.config or the registry etc...
_shouldTraceWcf = true;
}
internal static bool ShouldTraceWcf
{
get { return _shouldTraceWcf; }
}
}
public class WcfTraceFilter : TraceFilter
{
public override bool ShouldTrace(TraceEventCache cache, string source, TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data)
{
// In here, check the static 'ShouldTraceWcf' property as well as the name of the originating TraceSource
if (source != null && source.StartsWith("System.ServiceModel") && !WcfDiagnosticsHelper.ShouldTraceWcf)
return false;
return true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在App.config中,您可以像这样配置TraceFilter:
<system.diagnostics>
<sources>
<source name="System.ServiceModel" propagateActivity="true" switchValue="Warning">
<listeners>
<add name="LocalXmlFile" initializeData="WcfTracing.svclog" type="System.Diagnostics.XmlWriterTraceListener">
<filter type="WCF.Diagnostics.WcfTraceFilter, WCF_Custom_TraceFilter"/>
</add>
</listeners>
</source>
</sources>
</system.diagnostics>
Run Code Online (Sandbox Code Playgroud)
**
请注意,通过编写自定义跟踪开关可以实现类似的行为.主要区别在于TraceSwitch应用于TraceSource,TraceFilter应用于TraceListener.但是,它会涉及更多.
| 归档时间: |
|
| 查看次数: |
5886 次 |
| 最近记录: |