Microsoft KB Archive/815314

= How to manage event logs using Visual C# .NET or Visual C# 2005 =

Article ID: 815314

Article Last Modified on 11/14/2007

-

APPLIES TO


 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# 2005 Express Edition

-





For a Microsoft Visual Basic .NET version of this article, see 814564.



IN THIS TASK
 * SUMMARY
 * Requirements
 * Find the Existing Logs on a Computer
 * Read and Write Logs to Local and Remote System
 * Clear Logs
 * Create and Delete Custom Logs
 * Receive Event Notifications
 * Complete Code Listing
 * Verify the Results
 * REFERENCES



SUMMARY
This step-by-step article describes how to access and customize Windows event logs using the Microsoft .NET Framework. With the EventLog class you can interact with Windows event logs. Using the EventLog class you can read from the existing logs, write entries to the event log, create or delete event sources, delete logs, and respond to log entries. The article also describes how to create new logs while creating an event source.

back to the top

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
 * The Microsoft .NET Framework
 * Microsoft Visual C# .NET or Microsoft Visual C# 2005.

This article assumes that you are familiar with the following topics:
 * Microsoft Visual C# .NET or Microsoft Visual C# 2005 Syntax
 * Microsoft Visual Studio .NET or Microsoft Visual Studio 2005 Environment
 * Error handling in the .NET Framework

back to the top

Find the Existing Logs on a Computer
You can find the existing logs on a computer by using the shared method GetEventLogs of the EventLog class. The GetEventLogs method searches for all event logs on the local computer, and creates an array of EventLog objects that contain the list. The following example retrieves a list of logs on the local computer, and then displays the name of the log in a console window. EventLog[] remoteEventLogs; // Gets logs on the local computer, gives remote computer name to get the logs on the remote computer. remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName); Console.WriteLine(&quot;Number of logs on computer: &quot; + remoteEventLogs.Length);

for ( int i=0; i<remoteEventLogs.Length; i++ ) Console.WriteLine(&quot;Log: &quot; + remoteEventLogs[i].Log);

back to the top

Read logs
To read an event log, use the Entries properties of the EventLog class. The EventLog class Entries property is a collection of all the entries in the event log. You can iterate through this collection, and read all the entries in the specified log. The following code demonstrates how to do this: //logType can be Application, Security, System or any other Custom Log. string logType = &quot;Application&quot;; EventLog ev = new EventLog(logType, System.Environment.MachineName); int LastLogToShow = ev.Entries.Count; if ( LastLogToShow <= 0 ) Console.WriteLine(&quot;No Event Logs in the Log :&quot; + logType);

// Read the last 2 records in the specified log. int i; for ( i = ev.Entries.Count - 1; i>= LastLogToShow - 2; i--) {   EventLogEntry CurrentEntry = ev.Entries[i]; Console.WriteLine(&quot;Event ID : &quot; + CurrentEntry.EventID); Console.WriteLine(&quot;Entry Type : &quot; + CurrentEntry.EntryType.ToString); Console.WriteLine(&quot;Message : &quot; + CurrentEntry.Message + &quot;\n&quot;); }  ev.Close;

Write Logs
To write an event log, use the WriteEntry method of the EventLog class. To write the event log successfully, your application must have write access to the log that it is trying to write to. For more information about the permissions that you must have to read and write in an event log, visit the following Microsoft Web site.

Security Ramification of Event Logs

http://msdn2.microsoft.com/en-us/library/4xz6w79h(vs.71).aspx

You must set the source property on your EventLog component instance before you can write entries to a log. When your component writes an entry, the system automatically verifies to see if the source that you specified is registered with the event log that the component is writing to, and then calls CreateEventSource (if CreateEventSource must be called). //See if the source exists. if ( ! ( EventLog.SourceExists(&quot;MySystemSource&quot;, System.Environment.MachineName))) EventLog.CreateEventSource(&quot;MySystemSource&quot;, &quot;System&quot;, System.Environment.MachineName); EventLog ev = new EventLog(&quot;System&quot;, System.Environment.MachineName, &quot;MySystemSource&quot;); /* Writing to system log, in the similar way you can write to other * logs that you have appropriate permissions to write to */ ev.WriteEntry(&quot;Warning is written to system Log&quot;, EventLogEntryType.Warning, 10001); MessageBox.Show(&quot;Warning is written to System Log&quot;); ev.Close; back to the top

Clear Logs
When an event log is full, it stops recording new event information, or begins to overwrite earlier entries. If event recording stops, you can clear the log of existing entries, and allow the log to start recording events again. Call the Clear method on the event log component instance.

Note To clear event log entries, you must have administrator permissions on the computer where the log is. //Create an EventLog instance and pass log name and MachineName where the log resides. EventLog ev = new EventLog(&quot;Security&quot;, System.Environment.MachineName); ev.Clear; ev.Close; back to the top

Create the Custom Log
You can use the CreateEventSource method to create your own custom event handler. Before you create an event log, use the SourceExists method to verify that the source that you are using does not already exist, and then call the CreateEventSource. If you try to create a event log that already exists, System.ArgumentException is thrown. // Create the source, if it does not already exist. if (! (EventLog.SourceExists(&quot;MyOldSource&quot;, System.Environment.MachineName))) EventLog.CreateEventSource(&quot;MyOldSource&quot;, &quot;MyNewLog&quot;, System.Environment.MachineName); Console.WriteLine(&quot;CreatingEventSource&quot;);

Delete the Custom Log
To delete the event log, you can use the Delete method of the EventLog class. More than one source may write to an event log. Therefore, before you delete a custom log, make sure that there are no other sources that are writing to that log. string logName = &quot;MyNewLog&quot;; if ( EventLog.SourceExists(&quot;MyOldSource&quot;, System.Environment.MachineName)) {   logName = EventLog.LogNameFromSourceName(&quot;MyOldSource&quot;, System.Environment.MachineName); EventLog.DeleteEventSource(&quot;MyOldSource&quot;, System.Environment.MachineName); EventLog.Delete(logName, System.Environment.MachineName); Console.WriteLine(logName + &quot; deleted.&quot;); }   back to the top

Receive Event Notifications
You can receive event notification when an entry is written to a particular log. To do this, implement the EntryWritten event handler for the instance of the EventLog. Also, set EnableRaisingEvents to true.

Note You can only receive event notifications when entries are written on the local computer. You cannot receive notifications for entries that are written on remote computers.

back to the top

Complete Code Listing
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Security; using System.IO; using System.Diagnostics;

namespace WindowsApplication1 {   ///     /// Summary description for Form1. ///    public class Form1 : System.Windows.Forms.Form {       private System.Diagnostics.EventLog eventLog1; private System.Windows.Forms.Button btnListLog; private System.Windows.Forms.Button btnReadLog; private System.Windows.Forms.Button btnWriteLog; private System.Windows.Forms.Button btnClearLog; private System.Windows.Forms.Button btnCreateLog; private System.Windows.Forms.Button btnDeleteLog; private System.Windows.Forms.Button btnRecNotice; ///        /// Required designer variable. ///        private System.ComponentModel.Container components = null;

public Form1 {           //            // Required for Windows Form Designer support. //           InitializeComponent;

//           // TODO: Add any constructor code after InitializeComponent call. //       }

///        /// Clean up any resources that are being used. ///        protected override void Dispose( bool disposing ) {           if( disposing ) {               if (components != null) {                   components.Dispose; }           }            base.Dispose( disposing ); }

#region Windows Form Designer generated code ///        /// Required method for Designer support - do not modify /// the contents of this method with the code editor. ///        private void InitializeComponent {           this.eventLog1 = new System.Diagnostics.EventLog; this.btnListLog = new System.Windows.Forms.Button; this.btnReadLog = new System.Windows.Forms.Button; this.btnWriteLog = new System.Windows.Forms.Button; this.btnClearLog = new System.Windows.Forms.Button; this.btnCreateLog = new System.Windows.Forms.Button; this.btnDeleteLog = new System.Windows.Forms.Button; this.btnRecNotice = new System.Windows.Forms.Button; ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit; this.SuspendLayout; //            // eventLog1 //            this.eventLog1.MachineName = System.Environment.MachineName; this.eventLog1.SynchronizingObject = this; this.eventLog1.EntryWritten += new System.Diagnostics.EntryWrittenEventHandler(this.eventLog1_EntryWritten);

//            // btnListLog //            this.btnListLog.Location = new System.Drawing.Point(32, 16); this.btnListLog.Name = &quot;btnListLog&quot;; this.btnListLog.Size = new System.Drawing.Size(152, 23); this.btnListLog.TabIndex = 0; this.btnListLog.Text = &quot;List Event Logs&quot;; this.btnListLog.Click += new System.EventHandler(this.btnListLog_Click); //            // btnReadLog //            this.btnReadLog.Location = new System.Drawing.Point(32, 46); this.btnReadLog.Name = &quot;btnReadLog&quot;; this.btnReadLog.Size = new System.Drawing.Size(152, 23); this.btnReadLog.TabIndex = 1; this.btnReadLog.Text = &quot;Read Event Logs&quot;; this.btnReadLog.Click += new System.EventHandler(this.btnReadLog_Click); //            // btnWriteLog //            this.btnWriteLog.Location = new System.Drawing.Point(32, 77); this.btnWriteLog.Name = &quot;btnWriteLog&quot;; this.btnWriteLog.Size = new System.Drawing.Size(152, 23); this.btnWriteLog.TabIndex = 2; this.btnWriteLog.Text = &quot;Write Event Logs&quot;; this.btnWriteLog.Click += new System.EventHandler(this.btnWriteLog_Click); //            // btnClearLog //            this.btnClearLog.Location = new System.Drawing.Point(32, 106); this.btnClearLog.Name = &quot;btnClearLog&quot;; this.btnClearLog.Size = new System.Drawing.Size(152, 23); this.btnClearLog.TabIndex = 3; this.btnClearLog.Text = &quot;Clear Logs&quot;; this.btnClearLog.Click += new System.EventHandler(this.btnClearLog_Click);

//            // btnCreateLog //            this.btnCreateLog.Location = new System.Drawing.Point(32, 137); this.btnCreateLog.Name = &quot;btnCreateLog&quot;; this.btnCreateLog.Size = new System.Drawing.Size(152, 23); this.btnCreateLog.TabIndex = 4; this.btnCreateLog.Text = &quot;Create Custom Logs&quot;; this.btnCreateLog.Click += new System.EventHandler(this.btnCreateLog_Click);

//            // btnDeleteLog //            this.btnDeleteLog.Location = new System.Drawing.Point(32, 168); this.btnDeleteLog.Name = &quot;btnDeleteLog&quot;; this.btnDeleteLog.Size = new System.Drawing.Size(152, 23); this.btnDeleteLog.TabIndex = 5; this.btnDeleteLog.Text = &quot;Delete Custom Logs&quot;; this.btnDeleteLog.Click += new System.EventHandler(this.btnDeleteLog_Click); //            // btnRecNotice //            this.btnRecNotice.Location = new System.Drawing.Point(32, 199); this.btnRecNotice.Name = &quot;btnRecNotice&quot;; this.btnRecNotice.Size = new System.Drawing.Size(152, 23); this.btnRecNotice.TabIndex = 6; this.btnRecNotice.Text = &quot;Receive Event Notifications&quot;; this.btnRecNotice.Click += new System.EventHandler(this.btnRecNotice_Click);

//            // Form1 //            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(216, 237); this.Controls.Add(this.btnRecNotice); this.Controls.Add(this.btnDeleteLog); this.Controls.Add(this.btnCreateLog); this.Controls.Add(this.btnClearLog); this.Controls.Add(this.btnWriteLog); this.Controls.Add(this.btnReadLog); this.Controls.Add(this.btnListLog); this.Name = &quot;Form1&quot;; this.Text = &quot;Form1&quot;; ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit; this.ResumeLayout(false);

}       #endregion

///        /// The main entry point for the application. ///        [STAThread] static void Main {           Application.Run(new Form1); }

private void btnListLog_Click(object sender, System.EventArgs e)       { EventLog[] remoteEventLogs; // Gets logs on the local computer, gives remote computer name to get the logs on the remote computer. remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName);

Console.WriteLine(&quot;Number of logs on computer: &quot; + remoteEventLogs.Length);

for ( int i=0; i<remoteEventLogs.Length; i++ ) Console.WriteLine(&quot;Log: &quot; + remoteEventLogs[i].Log); }

private void btnReadLog_Click(object sender, System.EventArgs e)       {

//logType can be Application, Security, System or any other Custom Log. string logType = &quot;Application&quot;; /* In this case the EventLog constructor is passed a string variable for the log name and * second argument mention the computer name that you want to read the logs from, * and that you have appropriate permissions to*/

EventLog ev = new EventLog(logType, System.Environment.MachineName);

int LastLogToShow = ev.Entries.Count; if ( LastLogToShow <= 0 ) Console.WriteLine(&quot;No Event Logs in the Log :&quot; + logType); // Read the last 2 record in the specified log. int i;           for ( i = ev.Entries.Count - 1; i>= LastLogToShow - 2; i--) {               EventLogEntry CurrentEntry = ev.Entries[i]; Console.WriteLine(&quot;Event ID : &quot; + CurrentEntry.EventID); Console.WriteLine(&quot;Entry Type : &quot; + CurrentEntry.EntryType.ToString); Console.WriteLine(&quot;Message : &quot; + CurrentEntry.Message + &quot;\n&quot;); }

ev.Close;

/* Similarly you can loop through all the entries in the log using * the entries collection as shown in the following commented code. * For Each entry In ev.Entries */ }

private void btnWriteLog_Click(object sender, System.EventArgs e)       { /* When writing to an event log, pass the computer name where * the log resides. Here the MachineName Property of the Environment class * is used to determine the name of the local computer. Assuming that you have * the appropriate permissions, it is also easy to write to event logs on             * other computers.*/

//See if the Source exists. if ( ! ( EventLog.SourceExists(&quot;MySystemSource&quot;, System.Environment.MachineName))) EventLog.CreateEventSource(&quot;MySystemSource&quot;, &quot;System&quot;, System.Environment.MachineName); EventLog ev = new EventLog(&quot;System&quot;, System.Environment.MachineName, &quot;MySystemSource&quot;); /* Writing to system log, in the similar way you can write to other * logs that you have appropriate permissions to write to            */ ev.WriteEntry(&quot;Warning is written to system Log&quot;, EventLogEntryType.Warning, 10001); MessageBox.Show(&quot;Warning is written to System Log&quot;); ev.Close; }

private void btnClearLog_Click(object sender, System.EventArgs e)       { //Create an EventLog instance, and pass log name and MachineName where the log resides. EventLog ev = new EventLog(&quot;Security&quot;, System.Environment.MachineName); ev.Clear; ev.Close; }

private void btnCreateLog_Click(object sender, System.EventArgs e)       { // Create the source, if it does not already exist. if (! (EventLog.SourceExists(&quot;MyOldSource&quot;, System.Environment.MachineName))) // Creating a new log EventLog.CreateEventSource(&quot;MyOldSource&quot;, &quot;MyNewLog&quot;, System.Environment.MachineName); Console.WriteLine(&quot;CreatingEventSource&quot;); }

private void btnDeleteLog_Click(object sender, System.EventArgs e)       { string logName = &quot;MyNewLog&quot;;

if ( EventLog.SourceExists(&quot;MyOldSource&quot;, System.Environment.MachineName)) {               logName = EventLog.LogNameFromSourceName(&quot;MyOldSource&quot;, System.Environment.MachineName); EventLog.DeleteEventSource(&quot;MyOldSource&quot;, System.Environment.MachineName); EventLog.Delete(logName, System.Environment.MachineName); Console.WriteLine(logName + &quot; deleted.&quot;); }                   }

private void btnRecNotice_Click(object sender, System.EventArgs e)       { // Create the source, if it does not already exist. if (EventLog.SourceExists(&quot;MySource&quot;, System.Environment.MachineName) == false) {               EventLog.CreateEventSource(&quot;MySource&quot;, &quot;Application&quot;, System.Environment.MachineName); Console.WriteLine(&quot;CreatingEventSource&quot;); }

eventLog1.Log = &quot;Application&quot;; //Enable EnableRaisingEvents to true eventLog1.EnableRaisingEvents = true; EventLog.WriteEntry(&quot;MySource&quot;, &quot;EntryWritten event is fired&quot;, EventLogEntryType.Information); }

private void eventLog1_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)       { if (e.Entry.Source == &quot;MySource&quot;) Console.WriteLine(&quot;Entry written by my app. Message: &quot; + e.Entry.Message); }   } } back to the top

Verify the Results
To verify the results, follow these steps:
 * 1) In Microsoft Visual Studio .NET or in Microsoft Visual Studio 2005, create a new Visual C# .NET or Visual C# 2005 Windows Application project. By default, Form1.vb is created.
 * 2) Replace the code in Form1.vb with the code that is listed in the &quot;Complete Code Listing&quot; section of this article.
 * 3) On the Debug menu, click Start to run the application.
 * 4) Perform various actions on the form.
 * 5) On the View menu, click Server Explorer to verify the results.
 * 6) Expand Servers, and then expand Your Computer Name.
 * 7) Under the computer name, expand Event Logs.

Note The Servers node of Server Explorer is not available in the Academic Edition of Visual C# .NET. In such cases, you can use the Windows Event Viewer to view the results of your application.
 * 1) Check Server Explorer to verify that all the tasks are performed correctly.

back to the top

