Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Beginning System.Diagnostics

0.00/5 (No votes)
30 Oct 2003 1  
This article helps you to start understanding System.Diagnostics namespace.

Introduction

Following are the important classes in Diagnostics namespace.

System.Diagnostics.EventLog

This component provides 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:

     
  • 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 event log:

Create an object of EventLog class as follows:

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

Call the WriteEntry method of the above class.

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

Close the writer.

Ev.close

How to read from event log:

Create object of EventLog class and EventLogEntry class as follows:

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

Loop through the entries.

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

Next

How to create new EventLog node:

Create object of 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:

  • 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 current process

Dim curProc As Process = Process.GetCurrentProcess()

Msgbox(curProc.WorkingSet.ToString() + _ 
 vbCrLf + curProc.StartTime.ToLongTimeString() _ 
 + curProc.TotalProcessorTime.ToString())

How to get list of modules loaded by 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 using the PerformanceCounter class, and calculate results from successive performance counter samples 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 PerformanceCounter component provide access to collections of counters, counter permissions, 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, create a custom performance counter that can be written to as well as read from and determine via code whether a performance counter is custom or built-in.

For details visit MSDN.

System.Diagnostics.Debug

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.

  • 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. Members are almost similar to the Debug class.

System.Diagnostics.StackTrace & System.Diagnostics.StackFrame

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

Dim st As New StackTrace(False)
'just going one level above in the stacktrace

Dim sf As StackFrame = st.GetFrame(1) 
mp_MethodName = sf.GetMethod().Name()
mp_MethodName = sf.GetMethod().DeclaringType().Name() & ":" & mp_MethodName

You will find good number of samples here.

System.Diagnostics.SymbolStore

The System.Diagnostics.SymbolStore namespace provides classes that allows you to read and write debug symbol information, such as 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here