跟踪应用程序和在应用程序中插入检测点Tracing and Instrumenting Applications

跟踪是指应用程序正在运行时监视其执行情况的方式。Tracing is a way for you to monitor the execution of your application while it is running. 可在开发 .NET Framework 应用程序时向其添加跟踪和调试检测,也可在开发应用程序时或在部署此应用程序之后使用此检测。You can add tracing and debugging instrumentation to your .NET Framework application when you develop it, and you can use that instrumentation both while you are developing the application and after you have deployed it. 可使用 System.Diagnostics.TraceSystem.Diagnostics.DebugSystem.Diagnostics.TraceSource 类将错误和应用程序执行的相关信息记录在日志、文本文件或其他设备中,以供将来分析。You can use the System.Diagnostics.Trace, System.Diagnostics.Debug, and System.Diagnostics.TraceSource classes to record information about errors and application execution in logs, text files, or other devices for later analysis.

术语“检测”是指监视或测量产品的性能级别和诊断错误的功能。The term instrumentation refers to an ability to monitor or measure the level of a product's performance and to diagnose errors. 在编程中,即指应用程序合并以下功能的能力:In programming, this means the ability of an application to incorporate:

  • 代码跟踪 - 接收运行时有关应用程序执行的信息性消息。Code tracing - Receiving informative messages about the execution of an application at run time.

  • 调试 - 跟踪并修复开发中的应用程序的编程错误。Debugging - Tracking down and fixing programming errors in an application under development. 有关详细信息,请参阅调试For more information, see Debugging.

  • 性能计数器 - 可用于跟踪应用程序性能的组件。Performance counters - Components that allow you to track the performance of your application. 有关更多信息,请参阅性能计数器For more information, see Performance Counters.

  • 事件日志 - 可用于接收和跟踪应用程序执行过程中重要事件的组件。Event logs - Components that allow you receive and track major events in the execution of your application. 有关更多信息,请参见 EventLog 类。For more information, see the EventLog class.

通过将跟踪语句置于代码中的关键位置来检测应用程序非常适合分布式应用程序。Instrumenting your application by placing trace statements at strategic locations in your code is especially useful for distributed applications. 通过使用跟踪语句,可检测应用程序,从而在出现故障时显示相关信息并监视应用程序的运行情况。By using trace statements you can instrument an application not only to display information when things go wrong, but also to monitor how well the application is performing.

TraceSource 类提供了增强的跟踪功能,可用来代替较旧的 TraceDebug 跟踪类的静态方法。The TraceSource class provides enhanced tracing features and can be used in place of the static methods of the older Trace and Debug tracing classes. 常见的 TraceDebug 类仍然使用广泛,但建议对新的跟踪命令(如 TraceEventTraceData)使用 TraceSource 类。The familiar Trace and Debug classes are still widely used, but the TraceSource class is recommended for new tracing commands, such as TraceEvent and TraceData.

TraceDebug 类相同,只不过 Trace 类的过程和函数默认编译为发布版本,Debug 类的并非如此。The Trace and Debug classes are identical, except that procedures and functions of the Trace class are compiled by default into release builds, but those of the Debug class are not.

TraceDebug 类提供了在开发期间或部署之后监视和检查应用程序性能的方法。The Trace and Debug classes provide the means to monitor and examine application performance either during development or after deployment. 例如,您可以使用 Trace 类跟踪在已部署的应用程序中发生的特定类型的操作(例如新建数据库连接),因而可以监视该应用程序的效率。For example, you can use the Trace class to track particular types of actions in a deployed application as they occur (for example, creation of new database connections), and can therefore monitor the application's efficiency.

代码跟踪和调试Code Tracing and Debugging

在开发过程中,使用 Debug 类的输出方法,可以在 Visual Studio 集成开发环境 (IDE) 的“输出”窗口中显示消息。During development, you can use the output methods of the Debug class to display messages in the Output window of the Visual Studio integrated development environment (IDE). 例如:For example:

Trace.WriteLine("Hello World!")  
Debug.WriteLine("Hello World!")  
System.Diagnostics.Trace.WriteLine("Hello World!");  
System.Diagnostics.Debug.WriteLine("Hello World!");  

上述每个示例将在“输出窗口”中显示“Hello World!”Each of these examples will display "Hello World!" 当应用程序在调试器中运行时。in the Output window when the application is run in the debugger.

由此,你可以根据应用程序在测试环境中的行为对它进行调试并优化其性能。This enables you to debug your applications and optimize their performance based on their behavior in your test environment. 在调试版本中调试应用程序时,可以打开 Debug 条件特性,以便接收所有调试输出。You can debug your application in your debug build with the Debug conditional attribute turned on so that you receive all debugging output. 当您的应用程序准备好发布时,可以在关闭 Debug 条件特性的情况下编译您的发布版本,使编译器不会在最终可执行文件中包含调试代码。When your application is ready for release, you can compile your release build without turning on the Debug conditional attribute, so that the compiler will not include your debugging code in the final executable. 有关详细信息,请参阅如何:使用跟踪和调试执行有条件编译For more information, see How to: Compile Conditionally with Trace and Debug. 有关应用程序的不同生成配置的详细信息,请参阅编译和生成For more information on different build configurations for your application, see Compiling and Building.

你也可以使用 Trace 类的方法来跟踪已安装的应用程序中的代码执行情况。You can also trace code execution in an installed application, using methods of the Trace class. 通过将跟踪开关置于代码中,可控制是否执行跟踪以及执行的范围。By placing Trace Switches in your code, you can control whether tracing occurs and how extensive it is. 这使你可以监视应用程序在生产环境中的状态。This lets you monitor the status of your application in a production environment. 对使用在多台计算机上运行的多个组件的业务应用程序而言,这一点尤其重要。This is especially important in a business application that uses multiple components running on multiple computers. 可通过配置文件控制如何在部署后使用开关。You can control how the switches are used after deployment through the configuration file. 有关详细信息,请参阅如何:创建、初始化和配置跟踪开关For more information, see How to: Create, Initialize and Configure Trace Switches.

开发要对其使用跟踪的应用程序时,应用程序代码中通常要包含跟踪和调试消息。When you are developing an application for which you intend to use tracing, you usually include both tracing and debugging messages in the application code. 准备好部署应用程序时,无需打开“调试”条件属性就可编译发布版本。When you are ready to deploy the application, you can compile your release build without turning on the Debug conditional attribute. 但是,也可以打开“跟踪”条件属性,以便编译器将跟踪代码包括到可执行文件中。However, you can turn on the Trace conditional attribute so that the compiler includes your trace code in the executable. 有关详细信息,请参阅如何:使用跟踪和调试执行有条件编译For more information, see How to: Compile Conditionally with Trace and Debug.

代码跟踪的阶段Phases of Code Tracing

代码跟踪有 3 个阶段:There are three phases of code tracing:

  1. 检测 - 向应用程序添加跟踪代码。Instrumentation — you add trace code to your application.

  2. 跟踪 - 跟踪代码向指定目标写入相应信息。Tracing — the tracing code writes information to the specified target.

  3. 分析 - 评估跟踪信息以确定和了解应用程序中的问题。Analysis — you evaluate the tracing information to identify and understand problems in the application.

开发过程中,所有调试和跟踪输出方法都默认将信息写入 Visual Studio 的输出窗口。During development, all debug and trace output methods write information to the Output window in Visual Studio by default. 在已部署的应用程序中,方法将跟踪信息写入所指定的目标。In a deployed application, the methods write tracing information to the targets you specify. 有关指定跟踪或调试的输出目标的详细信息,请参阅跟踪侦听器For more information on specifying an output target for tracing or debugging, see Trace Listeners.

以下内容概述了使用跟踪来分析和更正已部署的应用程序中的潜在问题时通常涉及的主要步骤。The following is an overall view of the major steps typically involved in using tracing to analyze and correct potential problems in deployed applications. 有关如何执行这些步骤的详细信息,请参阅相应链接。For more information on how to perform these steps, see the appropriate link.

若要在应用程序中使用跟踪To use tracing in an application
  1. 请思考部署应用程序后想要现场接收哪种跟踪输出。Consider which tracing output you will want to receive onsite after you have deployed the application.

  2. 创建一组开关。Create a set of switches. 有关详细信息,请参阅如何:配置跟踪开关For more information, see How to: Configure Trace Switches.

  3. 向应用程序代码添加跟踪语句。Add the trace statements to the application code.

  4. 确定要显示跟踪输出的位置并添加相应的侦听器。Determine where you want the tracing output to appear and add the appropriate listeners. 有关详细信息,请参阅创建和初始化跟踪侦听器For more information, see Creating and Initializing Trace Listeners.

  5. 测试和调试应用程序及其包含的跟踪代码。Test and debug your application and the tracing code it contains.

  6. 使用下面一个过程将应用程序编译为可执行代码:Compile the application into executable code using one of the following procedures:

    • 使用“构建”菜单以及“解决方案资源管理器”中“属性页”对话框的“调试”页。Use the Build menu along with the Debug page of the Property Pages dialog box in Solution Explorer. 在 Visual Studio 中编译时,请使用此选项。Use this when compiling in Visual Studio.

      - 或 -- or -

    • 对编译的命令行方法使用“跟踪”和“调试”编译器指令。Use the Trace and Debug compiler directives for the command-line method of compiling. 有关详细信息,请参阅使用跟踪和调试进行条件编译For more information, see Compiling Conditionally with Trace and Debug. 从命令行进行编译时,请使用此选项。Use this when compiling from the command line.

  7. 如果在运行时出现问题,请打开相应的跟踪开关。If a problem occurs during run time, turn on the appropriate trace switch. 有关详细信息,请参阅配置跟踪开关For more information, see Configuring Trace Switches.

    跟踪代码向指定目标写入跟踪消息,如屏幕、文本文件或事件日志。The tracing code writes tracing messages to a specified target, for example, a screen, a text file, or an event log. 跟踪侦听器集合中附带的侦听器类型确定目标。The type of listener you included in the Trace.Listeners collection determines the target.

  8. 分析跟踪消息以确定和了解应用程序中的问题。Analyze the tracing messages to identify and understand the problem in the application.

跟踪检测和分布式应用程序Trace Instrumentation and Distributed Applications

在创建分布式应用程序时,可能难以按要使用的方式测试应用程序。When you create a distributed application, you might find it difficult to test the application in the manner in which it will be used. 开发团队几乎都不能测试操作系统或 Web 浏览器(包括所有本地化的语言选项)的所有潜在组合,也不能模拟将同时访问应用程序的大量用户。Few development teams have the capability to test all possible combinations of operating systems or Web browsers (including all the localized language options), or to simulate the high number of users that will access the application at the same time. 在这些情况下,无法测试分布式应用程序将如何响应高容量、不同的设置和最终用户的唯一行为。Under these circumstances, you cannot test how a distributed application will respond to high volumes, different setups, and unique end-user behaviors. 此外,分布式应用程序的很多部件都不具有可直接与之交互或可用于查看这些部件的行为的用户界面。Also, many parts of a distributed application have no user interface with which you can interact directly or view the activity of those parts.

但是,可通过以下方式补偿此不足之处:启用分布式应用程序以描述系统管理员感兴趣的某些事件(尤其是故障事件),并检测应用程序(即,将跟踪语句置于代码中的关键位置)。However, you can compensate for this by enabling distributed applications to describe certain events of interest to system administrators, especially things that go wrong, by instrumenting the application — that is, by placing trace statements at strategic locations in your code. 由此,如果运行时发生意外事件(例如,响应时间过于缓慢),就可确定可能的原因。Then if something unexpected occurs at run time (for example, excessively slow response time), you can determine the likely cause.

借助跟踪语句,可避免执行以下艰难任务:检查原始源代码、对其进行修改、重新编译以及试图在调试环境中生成运行时错误。With trace statements you can avoid the difficult task of examining the original source code, modifying it, recompiling, and attempting to produce the run-time error within the debugging environment. 请记住,检测应用程序这一操作可用于显示错误以及监视性能。Remember that you can instrument an application not only to display errors, but also to monitor performance.

将跟踪语句置于关键位置Strategic Placement of Trace Statements

放置供运行时期间使用的跟踪语句时,必须特别小心。You must exercise special care when placing your trace statements for use during run time. 注意考虑部署的应用程序中可能需要什么跟踪信息,以便充分涵盖所有可能的跟踪方案。You must consider what tracing information is likely to be needed in a deployed application, so that all likely tracing scenarios are adequately covered. 然而,使用跟踪的应用程序差别很大,因此关于将跟踪置于关键位置,没有通用准则。Because applications that use tracing vary widely, however, there are no general guidelines for strategic placement of tracing. 有关放置跟踪语句的详细信息,请参阅如何:向应用程序代码添加跟踪语句。For more information on placing trace statements, see How to: Add Trace Statements to Application Code.

跟踪的输出Output from Tracing

跟踪输出由名为“侦听器”的对象收集。Trace output is collected by objects called listeners. 侦听器是接收跟踪输出,并将它写入输出设备(通常为窗口、日志或文本文件)的对象。A listener is an object that receives trace output and writes it to an output device (usually a window, log, or text file). 跟踪侦听器在创建后,通常会被添加到 Trace.Listeners 集合中,这样侦听器就可以接收所有跟踪输出。When a trace listener is created, it is typically added to the Trace.Listeners collection, allowing the listener to receive all trace output.

在任何情况下,跟踪信息至少会写入默认的 Trace 输出目标 DefaultTraceListenerTracing information is always written at least to the default Trace output target, the DefaultTraceListener. 如果您因为某种原因删除了 DefaultTraceListener 而没有在 Listeners 集合中添加任何其他侦听器,则将收不到任何跟踪消息。If for some reason you have deleted the DefaultTraceListener without adding any other listeners to the Listeners collection, you will not receive any tracing messages. 有关详细信息,请参阅跟踪侦听器For more information, see Trace Listeners.

下表列出了六个写入跟踪信息的 Debug 成员和 Trace 方法。The six Debug members and Trace methods that write tracing information are listed in the following table.

方法Method OutputOutput
AssertAssert 指定的文本;若未指定,则为调用堆栈。The specified text; or, if none is specified, the Call Stack. 只有指定为“Assert”语句中的自变量的条件为“false”时,才写入输出。The output is written only if the condition specified as an argument in the Assert statement is false.
失败Fail 指定的文本;若未指定,则为调用堆栈。The specified text; or, if none is specified, the Call Stack.
WriteWrite 指定的文本。The specified text.
WriteIfWriteIf 如果满足指定为“WriteIf”语句中的自变量的条件,则为指定的文本。The specified text, if the condition specified as an argument in the WriteIf statement is satisfied.
WriteLineWriteLine 指定的文本和一个回车符。The specified text and a carriage return.
WriteLineIfWriteLineIf 如果满足指定为“WriteIf”语句中的自变量的条件,则为指定的文本和一个回车符。The specified text and a carriage return, if the condition specified as an argument in the WriteLineIf statement is satisfied.

Listeners 集合中所有的侦听器都会接收到上表中介绍的消息,但种类不同的侦听器在接到消息后所执行的操作可能也不同。All listeners in the Listeners collection receive the messages described in the above table, but the actions taken may vary depending on what kind of listener receives the message. 例如,DefaultTraceListener 将在接收到“Fail”或失败的“Assert”通知时显示一个断言对话框,而 TextWriterTraceListener 仅将输出写入它的流中。For example, the DefaultTraceListener displays an assertion dialog box when it receives a Fail or failed Assert notification, but a TextWriterTraceListener simply writes the output to its stream.

可通过实现自己的侦听器生成自定义结果。You can produce custom results by implementing your own listener. 例如,自定义跟踪侦听器可能将消息显示给消息框,或连接到数据库以将消息添加到表中。A custom trace listener might, for example, display the messages to a message box, or connect to a database to add messages to a table. 所有自定义侦听器都应支持上述 6 种方法。All custom listeners should support the six methods mentioned above. 有关创建开发人员定义的侦听器的详细信息,请参阅 .NET Framework 参考中的 TraceListenerFor more information on creating developer-defined listeners, see TraceListener in the .NET Framework reference.

“Write”和“WriteLine”方法始终写入指定的文本。The Write and WriteLine methods always write the text that you specify. “Assert”、“WriteIf”和“WriteLineIf”需要布尔型自变量,该自变量控制它们是否写入指定的文本;只有在表达式为“true”(对于“WriteIf”和“WriteLineIf”),或“false”(对于“Assert”)时,它们才会写入指定的文本。Assert, WriteIf, and WriteLineIf require a Boolean argument that controls whether or not they write the specified text; they write the specified text only if the expression is true (for WriteIf and WriteLineIf), or false (for Assert). “Fail”方法始终写入指定的文本。The Fail method always writes the specified text. 有关详细信息,请参阅如何:将跟踪语句添加到应用程序代码和 .NET Framework 引用。For more information, see How to: Add Trace Statements to Application Code and the .NET Framework reference.

安全问题Security Concerns

如果在部署 ASP.NET 应用程序之前未禁用跟踪和调试,你的应用程序可能会泄漏自身的相关信息,从而被恶意程序利用。If you do not disable tracing and debugging before deploying an ASP.NET application, your application may reveal information about itself that could be exploited by a malicious program. 有关详细信息,请参阅如何:通过跟踪和调试编译和生成进行条件编译, 以及如何:创建、初始化和配置跟踪开关For more information, see How to: Compile Conditionally with Trace and Debug, Compiling and Building, and How to: Create, Initialize and Configure Trace Switches. 也可通过 Internet 信息服务 (IIS) 配置调试。Debugging is also configurable through Internet Information Services (IIS).

请参阅See also