Working with Event Logs



Working with Event Logs

Instrument and debug a Windows service, a serviced component, a .NET Remoting object, and an XML Web service.

Event logging isthe standard way on the Windows platform for applications to log their events. You can easily monitor an application's behavior by using the Event Viewer utility to analyze its messages in the event log. In fact, you can also view events from the Visual Studio .NET environment, and you can access event logs through Server Explorer.

The Framework Class Library provides a set of classes especially designed to work with event logs. With the help of these classes, you can programmatically read from or write to event logs. Programmatic access might even allow you to automate some of the administrative tasks associated with an application.

By default, three event logs are available: Application, Security, and System. Other applications (including .NET applications) or operating system components, such as Active Directory, might add other event logs. Figure lists the important members of the EventLog class.

Figure Important Members of the EventLog Class

Member

Type

Description

CreateEventSource()

Method

Opens an event source so that an application can write event information

Delete()

Method

Removes a log resource

DeleteEventSource()

Method

Removes an application's event source from the event log

Entries

Property

Gets the contents of the event log

Exists()

Method

Determines whether the specified log exists

Log

Property

Specifies the name of the log to read from or write to

LogDisplayName

Property

Represents a friendly name for the event log

LogNameFromSourceName()

Method

Gets the name of the log to which the specified source is registered

MachineName

Property

Specifies the name of the computer on which to read or write events

Source

Property

Specifies the source to register and use when writing to an event log

SourceExists()

Method

Finds whether a given event source exists

WriteEntry()

Method

Writes an entry in the event log

EXAM TIP

Security Issues A program must have administrative privileges to create an event log. This is especially important in the case of ASP.NET because the ASP.NET worker process runs under a low-privilege account. The easiest way to ensure that the ASP.NET worker process has sufficient privilege is to configure ASP.NET to use the system account rather than the machine account. Alternatively, you can use the .NET Framework's security facilities to grant permissions on an assembly-by-assembly basis. For more details on these topics, see Chapter 11, "Security Issues."


NOTE

The Log Property Only the first eight characters of a Log name are significantly identified. So an event log with the name StepByStep9_11 is the same as StepByStep9_12.


Each application interested in interacting with an event log must register an event source with the log. After an event source is registered, its information is stored in the system Registry and is available across application restarts.

The CreateEventSource() method allows you to register the application with an event log; if the event log does not already exist, this method creates it for you.

The WriteEntry() method of the EventLog object allows you to write messages to the event log specified by the event source. If the event source specified by the Source property of an EventLog object does not exist, the first call to the WriteEntry() method creates the event source before writing the entry to the event log. You can write different types of messages (information, error, warning, success audit, and failure audit) to an event log. These types are specified by the values in the EventLogEntryType enumeration.

The sample Windows form in Step-by-Step 9.11 demonstrates how to create an event log, register an application with the event log, un-register an application with an event log, write to an event log, and delete an event log.

STEP BY STEP

9.11 Creating and Writing to an Event Log

  1. Add a Visual C# Windows application project to the solution. Name the project StepByStep9_11.

  2. Rename the Form1.cs file StepByStep9_11.cs in the project. Switch to the form's code view and modify all references to Form1 so that they refer to StepByStep9_11 instead.

  3. Place two GroupBox controls, three Label controls, one TextBox control (txtMessage, with MultiLine set to true), four Button controls (btnCreate, btnRemoveSource, btnRemoveLog, and btnWrite), one ComboBox control (cbEventLogs), and five RadioButton controls (rbError, rbInformation, rbFailureAudit, rbSuccessAudit, and rbWarning) on the form. Arrange the controls as shown in Figure.

    Figure. The StepByStep9_11 form uses the EventLog class to create an event log and write entries to it.

    graphics/09fig36.jpg

  4. Switch to the code view. Add the following using directive:

    
    using System.Diagnostics;
    
    
  5. Add the following code in the class definition:

    
    // Create a member to hold EventLogEntryType
    
    private EventLogEntryType eletEntryType =
    
       EventLogEntryType.Error;
    
    
  6. Add a new method named PopulateLogNames() to the class definition and call it from the form's Load event handler:

    
    private void StepByStep9_11_Load(
    
        object sender, System.EventArgs e)
    
    {
    
        PopulateLogNames();
    
    }
    
    private void PopulateLogNames()
    
    {
    
        cbEventLogs.Items.Clear();
    
        // Add eventlogs in to the combo box.
    
        foreach(EventLog el in
    
            EventLog.GetEventLogs())
    
            cbEventLogs.Items.Add(el.Log);
    
    }
    
    
  7. Attach a Click event handler to each Button control. Add the following code in the event handlers:

    
    private void btnCreate_Click(
    
        object sender, System.EventArgs e)
    
    {
    
        if (cbEventLogs.Text != "")
    
        {
    
            string strSourceName = "StepByStep9_11_"
    
                                 + cbEventLogs.Text;
    
            // Check whether the source already exists
    
            if (!EventLog.SourceExists(strSourceName))
    
            {
    
                try
    
                {
    
                    // Create event source and the
    
                    // event log (if log doesn't exist)
    
                    EventLog.CreateEventSource(
    
                       strSourceName,cbEventLogs.Text);
    
                    PopulateLogNames();
    
                    MessageBox.Show(
    
                        "Created EventSource " +
    
                        "for Selected EventLog");
    
                }
    
                catch(Exception ex)
    
                {
    
                    MessageBox.Show(ex.Message);
    
                }
    
            }
    
            else
    
                MessageBox.Show("You already have an " +
    
                "EventSource attached to this EventLog",
    
                "Cannot Create EventSource");
    
        }
    
    }
    
    
    
    private void btnRemoveSource_Click(
    
        object sender, System.EventArgs e)
    
    {
    
        if (cbEventLogs.Text != "")
    
        {
    
            string strSourceName = "StepByStep9_11" +
    
                                   cbEventLogs.Text;
    
            if (EventLog.SourceExists(strSourceName))
    
            {
    
                // Delete the Event Source
    
                EventLog.DeleteEventSource(strSourceName);
    
                MessageBox.Show("Deleted the EventSource "
    
                   + "for Selected EventLog");
    
            }
    
            else
    
                MessageBox.Show("There is currently no " +
    
                  "EventSource for selected EventLog");
    
        }
    
    }
    
    
    
    private void btnRemoveLog_Click(
    
        object sender, System.EventArgs e)
    
    {
    
    
    
        string strLogName = cbEventLogs.Text.ToUpper();
    
        // Do not delete system created logs
    
        if (strLogName == "APPLICATION" ||
    
            strLogName == "SECURITY" ||
    
            strLogName == "SYSTEM")
    
        {
    
            string strMessage = "This program does not " +
    
                "allow the deletion of system " +
    
                "created EventLogs as this may " +
    
                "cause undesirable effects on " +
    
                "the working of your computer.";
    
            MessageBox.Show(
    
               strMessage, "Dangerous Operation");
    
            return;
    
        }
    
        // If the log exists
    
        if (EventLog.Exists(cbEventLogs.Text))
    
        {
    
            // Confirm deletion from user
    
            string strMessage = "This operation will " +
    
             "delete the selected EventLog and " +
    
             "its associated EventSources, Are you Sure?";
    
            if(MessageBox.Show(
    
             strMessage, "Confirm Deletion",
    
             MessageBoxButtons.YesNo) == DialogResult.Yes)
    
                try
    
                {
    
                    // Delete the Event Log
    
                    EventLog.Delete(cbEventLogs.Text);
    
                    PopulateLogNames();
    
                }
    
                catch(Exception ex)
    
                {
    
                    MessageBox.Show(ex.Message,
    
                    "Error Deleting EventLog");
    
                }
    
        }
    
        else
    
            MessageBox.Show("Selected EventLog does " +
    
              "not Exists", "Cannot Delete EventLog");
    
    }
    
    
    
    private void btnWrite_Click(object sender,
    
                          System.EventArgs e)
    
    {
    
        if (cbEventLogs.Text != "")
    
        {
    
            string strSourceName = "StepByStep9_11_" +
    
               cbEventLogs.Text;
    
    
    
            // If Source exists
    
            if(EventLog.SourceExists(strSourceName))
    
                try
    
                {
    
                    // Write an entry into event log
    
                    EventLog.WriteEntry(strSourceName,
    
                                 this.txtMessage.Text,
    
                       this.eletEntryType);
    
                    MessageBox.Show(
    
                        "Entry written to the " +
    
                        "log successfully");
    
                }
    
                catch(Exception ex)
    
                {
    
                    MessageBox.Show(ex.Message,
    
                     "Cannot Write to selected EventLog");
    
                }
    
            else
    
                MessageBox.Show(
    
                    "There is no EventSource " +
    
                    "for selected EventLog",
    
                    "Event logging failed");
    
        }
    
        else
    
            MessageBox.Show("Please Select an EventLog " +
    
                       "to Write to.");
    
    }
    
    
  8. Add the following event handler in the class definition. Attach this event handler to all the RadioButton controls on the form:

    
    private void rbEventType_CheckedChanged(
    
        object sender, System.EventArgs e)
    
    {
    
        // Set the eletEntryType member
    
        if (sender == rbWarning)
    
            eletEntryType = EventLogEntryType.Warning;
    
        else if (sender == rbInformation)
    
            eletEntryType = EventLogEntryType.Information;
    
        else if (sender == rbSuccessAudit)
    
            eletEntryType =
    
                EventLogEntryType.SuccessAudit;
    
        else if (sender == rbFailureAudit)
    
            eletEntryType =
    
               EventLogEntryType.FailureAudit;
    
        else
    
            eletEntryType = EventLogEntryType.Error;
    
    }
    
    

    WARNING

    Deleting an Event Log You should use the Delete() method to delete an event log cautiously. When an event log is deleted, all event sources registered with it are also deleted, so no application can continue writing to that log. Do not attempt to delete an event log that was created by Windows or any other application that is important to you; if you do, those applications might crash or behave in unexpected ways.

  9. Set the project StepByStep9_11 as the startup project.

  10. Run the project. Enter a name in the ComboBox control to create a source and log in to the System event log. Select from the combo box the log in which you want to write, enter the message in the message text box, select the type of the message from the radio button options, and click the Write button to write to the event log.

  11. To view the logged messages, navigate to Server Explorer, expand the Servers node, and then select and expand the node that corresponds to your computer. Right-click the Events node and select Launch Event Viewer from the shortcut menu. This has the same effect as launching the Event Viewer from the Administrative Tools section of Windows Control Panel. Figure shows the contents of a custom event log that was created by using the project StepByStep9_11.

    37. You can use the Windows Event Viewer to view the contents of the event logs.

    graphics/09fig37.jpg

    NOTE

    Security Log The Security log is read-only for all users.