Chapter 6. Diagnostics

The .NET Framework Class Library (FCL) contains many classes to obtain diagnostic information about your application, as well as the environment it is running in. In fact, there are so many classes that a namespace, System.Diagnostics, was created to contain all of them. This chapter contains recipes for instrumenting your application with debug/trace information, obtaining process information, using the built-in Event Log, and taking advantage of performance counters.

Debugging (using the Debug class) is turned on by default in the debug build only, and tracing (using the Trace class) is turned on by default in both debug and release builds. These defaults allow you to ship your application instrumented with tracing code using the Trace class. You ship your code with tracing turned off so that the tracing code is not called (otherwise, the tracing would slow your application). If a problem that you cannot recreate on your development computer occurs on the production machine, you can enable tracing and allow the tracing information to be dumped to a file. This file can be inspected to help pinpoint the real problem. This trick is discussed at length in Recipe 6.1 and Recipe 6.2.

Since both the Debug and Trace classes contain the same members with the same names, they can be interchanged in your code by renaming Debug to Trace and vice versa. Most of the recipes in this chapter use the Trace class; you can modify those recipes so that they use the ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.