ExtendTracing 示例演示如何通过在客户端和服务代码中编写用户定义的活动跟踪来扩展 Windows Communication Foundation (WCF) 跟踪功能。 编写用户定义的活动跟踪允许用户创建跟踪活动和将跟踪分组到逻辑工作单元中。 还可以通过传输(在同一终结点内)和传播(跨终结点)关联活动。 在此示例中,为客户端和服务启用跟踪。 有关如何在客户端和服务配置文件中启用跟踪的详细信息,请参阅 跟踪和消息日志记录。
此示例基于入门指南。
注释
本示例的设置过程和生成说明位于本主题末尾。
跟踪和活动传播
用户定义的活动跟踪允许用户创建自己的跟踪活动,将跟踪分组到逻辑工作单元中,通过传输和传播关联活动,并降低 WCF 跟踪的性能成本(例如日志文件的磁盘空间成本)。
添加自定义源
可以将用户定义的跟踪添加到客户端和服务代码。 将跟踪源添加到客户端或服务配置文件允许在 服务跟踪查看器工具(SvcTraceViewer.exe)中记录和显示这些自定义跟踪。 以下代码演示如何添加名为 ServerCalculatorTraceSource
配置文件的用户定义跟踪源。
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Warning" propagateActivity="true">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="Default">
<filter type="" />
</add>
<add name="xml">
<filter type="" />
</add>
</listeners>
</source>
<source name="ServerCalculatorTraceSource" switchValue="Information,ActivityTracing">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="Default">
<filter type="" />
</add>
<add name="xml">
<filter type="" />
</add>
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="C:\logs\ServerTraces.svclog" type="System.Diagnostics.XmlWriterTraceListener"
name="xml" traceOutputOptions="Callstack">
<filter type="" />
</add>
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
....
关联活动
为在 propagateActivity
跟踪源中直接跨终结点关联活动,必须将 true
属性设置为 System.ServiceModel
。 此外,若要在不经历 WCF 活动的情况下进行跟踪传播,必须关闭 ServiceModel 活动跟踪功能。 可以在以下代码示例中看到这一点。
注释
关闭 ServiceModel 活动跟踪与将switchValue
属性的跟踪级别设置为“关闭”不同。
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Warning" propagateActivity="true">
...
</source>
</sources>
</system.diagnostics>
降低性能成本
在 ActivityTracing
跟踪源中 System.ServiceModel
设置为 off 会生成仅包含用户定义的活动跟踪的跟踪文件,而不包含任何 ServiceModel 活动跟踪。 排除 ServiceModel 活动跟踪会导致日志文件更小。 但会丢失关联 WCF 处理跟踪的机会。
设置、生成和运行示例
确保已为 Windows Communication Foundation 示例 执行One-Time 安装过程。
若要生成解决方案的 C# 或 Visual Basic .NET 版本,请按照 生成 Windows Communication Foundation 示例中的说明进行操作。
若要在单台或跨计算机配置中运行示例,请按照 运行 Windows Communication Foundation 示例 中的说明执行操作。