Export (0) Print
Expand All

Walkthrough: Exploring Event Logs, Event Sources, and Entries

This walkthrough will take you through the major feature areas of event logging in your Visual Studio application. During this walkthrough, you will learn how to:

  • Create an EventLog component.
  • Write code to create and delete custom event logs.
  • Write entries of various types to the custom log.
  • Read entries from the custom log.
  • Verify the existence of logs and event sources.
  • Clear log entries.
  • Use Server Explorer to verify the results of your event log actions.

Creating the User Interface

In this walkthrough, you will create a Windows Form and use a series of controls on it to launch a series of event-logging actions.

To create the form and controls for your application

  1. From the New Project dialog box, create a Visual Basic or C# Windows Application, and name it EventLogApp1.
  2. Add eight buttons to the Windows Form, and set the following properties for them:
    ControlText PropertyName Property
    Button1Create Custom LogCreateLog
    Button2Delete LogDeleteLog
    Button3Write EntryWriteEntry
    Button4Clear LogClearLog
    Button5Verify Log ExistsVerifyLog
    Button6Verify Source ExistsVerifySource
    Button7Remove Event SourceRemoveSource
    Button8Read EntryReadEntry
  3. In turn, do the following for each button:
    1. In the designer, double-click the button to create a default event handler for that button. The Code Editor appears and a sub for the button's Click event appears.
    2. Return to Design view, and double-click the next button.
    3. Continue until you have created a default event handler sub for each button.
  4. From the Components tab of the Toolbox, drag an EventLog component to the form.

    An EventLog component instance appears in the component tray area at the bottom of the form.

Creating and Deleting a Custom Log

In this procedure, you will use the SourceExists method to verify that the source you are using does not already exist, and then you will call the CreateEventSource method with the name of a log that does not exist. Because this log does not exist, the system will create a custom log for you when this code is run.

To create the custom log

  1. In the Code Editor, locate the CreateLog_Click procedure.
  2. Type in the following code. The event log and source are created as a pair, and the source cannot already exist before the event log is created. After creating the event log, the EventLog component is configured to access the new event log.
    ' Visual Basic
    ' Source cannot already exist before creating the log.
    If EventLog.SourceExists("Source1") Then
       EventLog.DeleteEventSource("Source1")
    End If
    
    ' Logs and Sources are created as a pair.
    EventLog.CreateEventSource("Source1", "NewLog1")
    ' Associate the EventLog component with the new log.
    EventLog1.Log = "NewLog1"
    EventLog1.Source = "Source1"
    
    // C#
    // Source cannot already exist before creating the log.
    if (System.Diagnostics.EventLog.SourceExists("Source1"))
    {
       System.Diagnostics.EventLog.DeleteEventSource("Source1");
    }
    
    // Logs and Sources are created as a pair.
    System.Diagnostics.EventLog.CreateEventSource("Source1", "NewLog1");
    // Associate the EventLog component with the new log.
    eventLog1.Log = "NewLog1";
    eventLog1.Source = "Source1";
    
    Security Note   When you create an event log, you need to decide what to do if that resource already exists. Another process, perhaps a malicious one, may have already created the event log and have access to it. When you put data in the event log, the data is available to the other process.

To delete a custom log

  1. In the Code Editor, locate the DeleteLog_Click procedure.
  2. Type in the following code:
    ' Visual Basic
    If EventLog.Exists("NewLog1") Then
       EventLog.Delete("NewLog1")
    End If
    
    // C#
    if (System.Diagnostics.EventLog.Exists("NewLog1"))
    {
       System.Diagnostics.EventLog.Delete("NewLog1");
    }
    

Writing Entries to the Log

In this procedure, you will use the EventLog component instance you created to write entries to the log. To do so, you will first configure the component to use the source string you just created, then you will specify two entries to write: an informational event and an error event.

To write entries to the log

  1. In the Code Editor, locate the WriteEntry_Click procedure.
  2. Type in the following code. This code uses the overloaded EventLog.WriteEntry method to write to the event log. The second form shown allows you to specify the type of message. If you view the entries using the Server Explorer in the "Testing Your Code" section below, the different types of entries are indicated by different icons.
    ' Visual Basic
    EventLog1.WriteEntry("This is an informational message")
    EventLog1.WriteEntry("This is an error message", _
       Diagnostics.EventLogEntryType.Error)
    
    // C#
    eventLog1.WriteEntry("This is an informational message");
    eventLog1.WriteEntry("This is an error message", 
       System.Diagnostics.EventLogEntryType.Error);
    

Clearing Log Entries

In this procedure, you will use the Clear method to remove existing entries from the custom log.

To clear log entries

  1. In the Code Editor, locate the ClearLog_Click procedure.
  2. Call the Clear method on the EventLog component instance:
    ' Visual Basic
    EventLog1.Clear()
    
    // C#
    eventLog1.Clear();
    

Verifying Logs and Sources

In this procedure, you will create two procedures: one that verifies the existence of the custom log, and one that verifies the existence of your source string. These procedures will be used to test the results of various actions you perform when you run the project.

To verify that the custom log exists

  1. In the Code Editor, locate the VerifyLog_Click procedure.
  2. Create a message box that evaluates whether the specified event log exists and displays true or false accordingly. Use this code:
    ' Visual Basic
    Dim logExists As Boolean = EventLog.Exists("NewLog1")
    MessageBox.Show("Does the log exist? " & logExists.ToString())
    
    // C#
    bool logExists = System.Diagnostics.EventLog.Exists("NewLog1");
    MessageBox.Show("Does the log exist? " + logExists.ToString());
    

To verify that the source exists

  1. In the Code Editor, locate the VerifySource_Click procedure.
  2. Create a message box that evaluates whether the specified source exists and displays true or false accordingly. Use this code:
    ' Visual Basic
    Dim sourceExists As Boolean = EventLog.SourceExists("Source1")
    MessageBox.Show("Does the source exist? " + sourceExists.ToString())
    
    // C#
    bool sourceExists = 
       System.Diagnostics.EventLog.SourceExists("Source1");
    MessageBox.Show("Does the source exist? " + sourceExists.ToString());
    

Removing Sources

In this procedure, you will write code to delete a source string. To do so, you will first verify that the source in question (Source1) exists, then call the DeleteEventSource method to remove it.

To remove the event source you created

  1. In the Code Editor, locate the RemoveSource_Click procedure.
  2. Add the following code:
    ' Visual Basic
    If EventLog.SourceExists("Source1") Then
       EventLog.DeleteEventSource("Source1")
    End If
    
    // C#
    if (System.Diagnostics.EventLog.SourceExists("Source1"))
    {
       System.Diagnostics.EventLog.DeleteEventSource("Source1");
    }
    

Reading Entries

In this procedure, you will write code to iterate through the event log's entries collection and display the existing messages in the log.

To read entries from the custom log you created

  1. In the Code Editor, locate the ReadEntry_Click procedure.
  2. Add the following code:
    ' Visual Basic
    Dim entry As EventLogEntry
    If EventLog1.Entries.Count > 0 Then
       For Each entry In EventLog1.Entries
          System.Windows.Forms.MessageBox.Show(entry.Message)
       Next
    Else
       MessageBox.Show("There are no entries in the log.")
    End If
    
    // C#
    if (eventLog1.Entries.Count > 0) 
    {
       foreach (System.Diagnostics.EventLogEntry entry 
          in eventLog1.Entries)
       {
          MessageBox.Show(entry.Message);
       }
    }
    else 
    {
       MessageBox.Show("There are no entries in the log.");
    }
    

Testing your Code

In this section, you will use Server Explorer to verify the results of your code.

Launching Server Explorer

  1. From the View menu, access Server Explorer.
  2. Expand the node for your current server, and then expand the Event Logs node beneath it.
    Note   The Servers node of Server Explorer is not available in the Standard Edition of Visual Basic and Visual C# .NET. For more information, see Visual Basic Standard Edition Features or Visual C# Standard Edition Features. In this case, you can use the Windows Event Viewer instead to view the results of your application.

Build and run your application

  1. Save your files and press F5 to build and launch your project. The form appears with the eight buttons you created.
  2. Click the Create Custom Log button.
    Note   You must have appropriate privileges to the server on which your application runs in order to create Windows event logs. If you receive a security error at this point, see your system administrator.
  3. Return to the product, while still in run mode, and right-click the Event Logs node in Server Explorer.
  4. Click Refresh.
  5. Verify that the NewLog1 log now appears in the Event Logs node.

To test creating, deleting, and verifying custom logs

  1. Return to your running form, and click the Verify Log Exists button.

    A prompt should appear with the text set to "True."

  2. Click the Delete Log button, and then click the Verify Log Exists button again.

    This time, the prompt should say "False."

  3. Click the Create Custom Log button again to recreate the log.

To test writing entries to and reading entries from the custom log

  1. In the form, click the Write Entry button.
  2. Access Server Explorer, and expand the NewLog1 log.
    Note   The Servers node of Server Explorer is not available in the Standard Edition of Visual Basic and Visual C# .NET. For more information, see Visual Basic Standard Edition Features or Visual C# Standard Edition Features.
  3. Expand the Source1 node beneath it.

    You should now see that two entries have been added to the log. One will have an icon indicating that it is an informational entry, and one will have an icon indicating that it is an error.

  4. Return to the form, and click the Read Entry button.

    You will receive two prompts: one containing the informational entry and one containing the error entry.

    Note   If you clicked the Write Entry button multiple times, you will have received more prompts.

To test clearing the log

  1. In the form, click the Clear Log button.
  2. In Server Explorer, right-click the NewLog1 node, and then click Refresh.

    You should now see that the log no longer contains entries.

To test removing the source string

  1. In the form, click the Remove Event Source button.
  2. Click the Verify Source button. You should receive a prompt that says "False" to indicate that the source Source1 no longer exists.
  3. Click the Write Entry button.
    Note   This action will allow you to write entries to the log, because the WriteEntry method will set the source if it does not currently exist.
  4. In Server Explorer, right-click the NewLog1 node, and then click Refresh. You should see two entries in the log.
  5. Click the Verify Source button again. You should receive a prompt that says "True" to indicate that the source Source1 exists.
  6. Optionally, you may want to click the DeleteLog button when you are through testing. This will remove the log NewLog1 and the source Source1 so that there are no permanent changes to your system's configuration.

See Also

System Monitoring Walkthroughs | Logging Application, Server, and Security Events

Show:
© 2014 Microsoft