Server Explorer
Although the Server Explorer is useful for interrogating a machine while writing your code, the true power comes with the component creation you get when you drag particular nodes onto a Windows form. For example, in this case, if you drag the Application node onto a Windows form, you get an instance of the System.Diagnostic.EventLog class added to the nonvisual area of the designer. You can then write an entry to this event log using the following code:
Private Sub ButtonClick(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
Me.EventLog1.Source = My.Settings.EventLogName Me.EventLog1.WriteEntry(“Button Clicked”, EventLogEntryType.Information)
End Sub
You can also write exception information using the WriteException method, which accepts an exception and a string that may provide additional debugging information. Unfortunately, you still have to manually set the Source property before calling the WriteEntry method. Of course, this could have been set using the Properties window for the EventLog1 component, but doing so would make it hardcoded into the application. Instead, this is provided as a setting in the configuration file.
An alternative to adding an EventLog class to your code is to use the built-in logging provided by the My namespace. For example, you can modify the previous code snippet to write a log entry using the
Application.Log property:
Private Sub ButtonClick(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
My.Application.Log.WriteEntry(“Button Clicked”, EventLogEntryType.Information)
End Sub
This is equivalent to the previous code, even to the extent of having the event source specified in the configuration file. Using the My namespace to write logging information also has a number of additional benefits. In the following configuration file, an EventLogTraceListener is specified to route log information to the event log. However, you can specify other trace listeners — for example, the FileLog TraceListener, which writes information to a log file by adding it to the SharedListeners and Listeners collections:
<?xml version=”1.0” encoding=”utf-8” ?> <configuration>
<system.diagnostics>
<sources>
<source name=”DefaultSource” switchName=”DefaultSwitch”> <listeners>
<add name=”EventLog”/> </listeners>
</source>
</sources>
<switches>
<add name=”DefaultSwitch” value=”Information” /> </switches>
<sharedListeners>
<add name=”EventLog” type=”System.Diagnostics.EventLogTraceListener” initializeData=”ApplicationEventLog”/>
</sharedListeners>
</system.diagnostics>
</configuration>