System.Diagnostics

Environment: .NET

Following are the important classes in the Diagnostics Namespace.

System.Diagnostics.EventLog

This component provides the functionality to write to event logs, read event log entries, and create and delete event logs and event sources on the network.

Some related Classes:

Class Description
EventLog Provides interaction with Windows event logs.
EventLogEntry Encapsulates a single record in the event log. This class cannot be inherited.
EventLogEntryCollection Defines size and enumerators for a collection of EventLogEntry instances.
EventLogInstaller Allows you to install and configure an event log that your application reads from or writes to when running. This class is called by the installation utility—for example, InstallUtil.exe—when installing an event log.
EventLogPermission Allows control of code access permissions for event logging.
EventLogPermissionAttribute Allows declarative permission checks for event logging.
EventLogPermissionEntry Defines the smallest unit of a code access security permission that is set for an EventLog.
EventLogPermissionEntryCollection Contains a strongly typed collection of EventLogPermissionEntry objects.
EventLogTraceListener Provides a simple listener that directs tracing or debugging output to an EventLog.

Examples

How to write to an event log

Create an object of EventLog class as follows:

Dim ev As New EventLog("Application", _
          System.Environment.MachineName, "MyAppName")

Call the write entry method of above class:

ev.WriteEntry("My event text", _
   System.Diagnostics.EventLogEntryType.Information, myeventid)

Close the writer:

Ev.close

How to read from the event log

Create an object of the eventlog class and the eventlog entry class as follows:

Dim ev As New EventLog("Application", _
          System.Environment.MachineName, "MyAppName")
Dim entry As EventLogEntry

Loop thru the entries:

For each entry in ev.Entries
    'Loop thru it. Entry.EventId, entry.Message, entry.EntryType
Next

How to create a new EventLog node

Create an object of the eventlog class as follows:

Dim ev As New EventLog(NodeNametobecreated, _
          System.Environment.MachineName, "Sourceoflog")
ev.WriteEntry("test message")
ev.Close()

System.Diagnostics.Process

The Process class provides functionality to monitor system processes across the network, and to start and stop local system processes.

In additional to retrieving lists of running processes (by specifying either the computer, the process name, or the process id) or viewing information about the process that currently has access to the processor, you can get detailed knowledge of process threads and modules both through the Process class itself, and by interacting with the ProcessThread and ProcessModule classes.

The ProcessStartInfo class enables you to specify a variety of elements with which to start a new process, such as input, output, and error streams, working directories, and command line verbs and arguments. These give you fine control over the behavior of your processes.

Other related classes let you specify window styles, process and thread priorities, and interact with collections of threads and modules.

Some related Classes

Class Description
Process Provides access to local and remote processes and enables you to start and stop local system processes
ProcessModule Represents a .dll or .exe file that is loaded into a particular process
ProcessModuleCollection Provides a strongly typed collection of ProcessModule objects
ProcessStartInfo Specifies a set of values used when starting a process
ProcessThread Represents an operating system process thread
ProcessThreadCollection Provides a strongly typed collection of ProcessThread objects

Examples

How to list all the running process:

Dim oPro as Process
For each oPro in Process.GetProcesses()
    MsgBox(ProcessInfo.ProcessName)
Next

How to start a process:

Dim oPro as Process
pPro = Process.Start("notepad.exe")
pPro.WaitForExit()

How to start a process with command line args:

Dim startInfo As New ProcessStartInfo("explorer.exe")
startInfo.Arguments = "/n"
Process.Start(startInfo)

How to get info about the current process:

Dim curProc As Process = Process.GetCurrentProcess()
Msgbox(curProc.WorkingSet.ToString() + vbCrLf + _
       curProc.StartTime.ToLongTimeString() + _
       curProc.TotalProcessorTime.ToString())

How to get a list of Modules loaded by the Process:

Dim ProcessInfo As Process = Process.GetProcessById(ProcessID)
Dim modl As ProcessModuleCollection = ProcessInfo.Modules
Dim strMod As New System.Text.StringBuilder()
Dim proMod As ProcessModule
For Each proMod In modl
    strMod.Append("Module Name: " + proMod.ModuleName + vbCrLf)
Next proMod

System.Diagnostics.PerformanceCounter

The PerformanceCounter class enables you to monitor system performance, while the PerformanceCounterCategory class provides a way to create new custom counters and categories.

You can write to local custom counters and read from both local and remote counters (system as well as custom). You can sample counters by using the PerformanceCounter class, and calculate results from successive performance counter samples by using the CounterSample class.

The CounterCreationData class enables you to create multiple counters in a category and specify their types. Other classes associated with the performance counter component provide access to collections of counters, counter permission, and counter types.

Example

How to list all the performance counters categories:

Dim myCategory As PerformanceCounterCategory
Dim myCategories() As PerformanceCounterCategory
myCategories = myCategory.GetCategories()
For Each myCategory In myCategories
    ' Loop thru it.
Next

Through this class, we are able to Reference an existing performance counter and read its value, creating a custom performance counter that can be written to as well as read fromDetermining via code whether a performance counter is custom or built-in. For details, visit http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbconIntroductionToMonitoringPerformanceThresholds.asp.

System.Diagnostics.Debug

This provides a set of methods and properties that help debug your code. This class cannot be inherited. We all are accustomed to this class. Following are the important methods of this class:

Method Description
Assert Overloaded. Checks for a condition and displays a message if the condition is false.
Write/WriteLine Writes information about the debug to the trace listeners in the Listeners collection.
WriteIf/ WriteLineIf Writes information about the debug to the trace listeners in the Listeners collection if a condition is true.

System.Diagnostics.Trace

This class provides a set of methods and properties that help you trace the execution of your code. You can use the properties and methods in the Trace class to instrument release builds. Instrumentation allows you to monitor the health of your application running in real-life settings.

The members are very similar to the Debug.

System.Diagnostics.StackTrace

System.Diagnostics.StackFrame

These classes will expose the stack information about the routines. The following example will return the name of the calling method.

Dim st As New StackTrace(False)
Dim sf As StackFrame = st.GetFrame(1)    ' just going one level
                                         ' above in the stacktrace
mp_MethodName = sf.GetMethod().Name()
mp_MethodName = sf.GetMethod().DeclaringType().Name() & ":" _
                & mp_MethodName

System.Diagnostics.SymbolStore

The System.Diagnostics.SymbolStore namespace provides classes that allow you to read and write debug symbol information, such as the source line to Microsoft intermediate language (MSIL) maps. Compilers targeting the .NET Framework can store the debug symbol information into programmer’s database (PDB) files. Debuggers and code profiler tools can read the debug symbol information at run time.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read