School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!
Welcome to Dream.In.Code
Become an Expert!

Join 340,149 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 3,878 people online right now. Registration is fast and FREE... Join Now!



Working with the System Event Log with C# (Intro)

Page 1 of 1

Working with the System Event Log with C# (Intro)

#1 PsychoCoder  Icon User is offline

  • apt-get install DIC.bin
  • Icon
  • View blog
  • Group: Admins
  • Posts: 16,214
  • Joined: 26-July 07


Dream Kudos: 12400

Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net, jQuery

Posted 16 March 2009 - 03:41 PM

This little tidbit is sparked by a question asked on the forum earlier. It was then that I realized that there isnt much content there regarding playing with the EventLog in C# (it really isnt as had as one may thing, trust me:) ).First thing we need to look at a few items in the System.Diagnostics Namespace.

Before moving on, the above Namespace is the one used for all interactions with the system, whether it be processes or Event Logs.

The two main classes we will be working with today are the The EventLog Class allows us to interact (read, write, delete, create new) with the Event Logs of the system. You can provide your instance of this class to connect to a different machine on a network.

The EventLogEntry Class encapulates each log into the Event Log. From this we can determine the error id, the application, the machine it happened on, when it happened and much more.

The first thing we want to look at is reading from an EventLog. You can retrieve each entry from each log, or you could shorten it by providing a log name (Application, System, etc..) and the machine name to search (can be left blank or as "." for the local system).

In this demonstration we will search an Event Log on the local system for all entries that contain a certain event id. We will loop through each of these entries and add each one to a Hashtable, we will then add each Hashtable to a Generic list. Let's take a look at how this is accomplished

/// <summary>
/// Function to return a generic listn of Hashtables containing each entry
/// from the requested entry type, event id, machine (in case doing it across a network)
/// source, and time logged are stored in their own Hashtable then added to the list
/// </summary>
/// <param name="logName">name of the log e.x; Application, Security, etc..</param>
/// <param name="machineName">Machine we're querying</param>
/// <param name="instanceId">The Event ID we're searching for</param>
/// <returns></returns>
/// <remarks></remarks>
public List<Hashtable> GetEventEntryByEvent(ref string logName, ref string machineName, ref long instanceId)
{
	try {
		//Create our list
		List<Hashtable> events = new List<Hashtable>();

		//Connect to the EventLog of the specified machine
		EventLog log = new EventLog(logName, machineName);

		//Now we want to loop through each entry
		foreach (EventLogEntry entry in log.Entries) {
			//If we run across one with the right entry id we create a new Hashtable
			//then we add the Message, InstanceId,Source, and TimeWritten values
			//from that entry
			if (entry.InstanceId == instanceId)
			{
				Hashtable entryInfo = new Hashtable();

				entryInfo.Add("Message", entry.Message);
				entryInfo.Add("InstanceId", entry.InstanceId);
				entryInfo.Add("Source", entry.Source);
				entryInfo.Add("TimeWritten", entry.TimeWritten);

				//Add this new Hashtable to our list
				events.Add(entryInfo);

				entryInfo = null;
			}
		}
		//Return the results
		return events;
	}
	catch (Exception ex) {
		MessageBox.Show(ex.ToString());
		return null;
	}
}



In our next example we will take a look at creating a new source and log to the system's Event Log. We will then write an entry to that new source we created.

/// <summary>
/// Function to add a new source, log name and a new entry to the new log
/// </summary>
/// <param name="source">Source of the new entry</param>
/// <param name="logName">Name of the log file to create</param>
/// <param name="message">Message to write to the entry</param>
/// <returns></returns>
/// <remarks></remarks>
public bool AddNewEntry(ref string source, ref string logName, ref string message)
{
	try {
		//First we need to make sure that this source doesnt exist yet
		if (!EventLog.SourceExists(source))
		{
			//Create our source by providing the source and the name of the
			//new log name
			EventLog.CreateEventSource(source, logName);

			//Due to latency we want to wait a bit for the source and
			//log to be created. So we will sleep for 3 seconds
			System.Threading.Thread.Sleep(3000);
		}

		//Now we need a new instance of the EventLog
		EventLog log = new EventLog();
		//Set the source we're writing to
		log.Source = source;

		//Now write an entry
		log.WriteEntry(message, EventLogEntryType.Information, 99);

		return true;
	}
	catch (Exception ex) {
		MessageBox.Show(ex.ToString());
		return false;
	}

}



Now we will take a look at writing an entry to an already existing log. In this demonstration we will first check to make sure the source exists, then we will make sure the log file provided exists. If either are true we throw a new Exception and exit the function, otherwise we write the new entry

// <summary>
/// Function to write a new entry to an existing source/log in the EventLog
/// </summary>
/// <param name="source">Source we're looking for</param>
/// <param name="logName">Log name we're looking for</param>
/// <param name="machineName">Machine we are looking on
/// NOTE#: Can leave the machine name to "." to search the local machine
/// </param>
/// <param name="message">Message we want in the entry</param>
/// <returns></returns>
/// <remarks></remarks>
public bool WriteNewEntry(ref string source, ref string logName, ref string machineName, ref string message)
{
	try {
		//Create a new instance of the EventLog class
		EventLog log = new EventLog(logName, machineName, source);

		//Make sure the source exists and the log name exists
		//if either is found a new exception is thrown and the function is exited
		if (EventLog.SourceExists(source))
		{
			//Make sure the log exists
			if (EventLog.Exists(logName))
			{
				//Write the new entry
				log.WriteEntry(message, EventLogEntryType.Information);
			}
			else
			{
				throw new Exception("Log name specified does not exist!");
				return;
			}
		}
		else
		{
			throw new Exception("The source name provided does not exist!");
			return;
		}
		return true;
	}
	catch (Exception ex) {
		MessageBox.Show(ex.ToString());
		return false;
	}
}



Well I hope you enjoyed this little walk down memory lane demonstration on working with the System Event Log with C#. I'm sure I'll end up writing a more advanced demonstration so keep your eyes out for it, and thanks for reading :)

Happy Coding!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1


Fast Reply

  

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users



Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month