Error Reporting To The EventLog - NUnit

For this article, we're going to write a class to write to the EventLog. To allow us for easy error logging.

I'm going to use NUnit as well to test our class. You can get NUnint at http://www.nunit.org/. Install it.

Start by creating a new project called 'EventLogTests', this is a class library. Add a reference to nunit.framework.dll located in the NUnit bin directory.

Throw out the constructor and add the attribute TestFixture to the class. This will tell NUnit about a new set of tests.
1namespace EventLogTests {

2 using System;
3 using NUnit.Framework;
4 using CumpsD.Tools;
5 using System.Diagnostics;
6
7 [TestFixture()]
8 public class EventLogTests {
9
10 } /* EventLogTests */
11} /* EventLogTests */
Now we'll add a method called Initialise, which we mark with the SetUp attribute. This method will be run at the beginning of each test. In here we will create our EventLogger object (which doesn't exist yet).
1private EventLogger _ErrorLog;

2
3[SetUp]
4public void Initialise() {
5 this._ErrorLog = new EventLogger("MyCatastrophicError");
6}
Next thing is setting up NUnit. You can find Visual Studio add-ins vor NUnit, but as I'm having some problems with getting them to work properly I'm using an alternate method. Go to the project properties, configuration properties, debugging. And set Debug Mode to Program, and Start Application to nunit-gui.exe, each time we'll press F5 NUnit will now launch.

The way of test driven development is to first write a test that fails and then add some code to make the test pass. We have already written a failing SetUp, because the EventLogger class doesn't exist yet, this counts as a failed test as well. So, let's make it pass.

Create a new class library called EventLogger and create the constructor.
1namespace CumpsD.Tools {

2 using System;
3 using System.Diagnostics;
4 using System.Runtime.Serialization;
5 using System.Runtime.Serialization.Formatters.Binary;
6 using System.Security;
7 using System.Security.Permissions;
8 using System.Globalization;
9
10 public class EventLogger {
11 private string _ApplicationName;
12 private EventLog _Log;
13
14 public string ApplicationName {
15 get { return this._ApplicationName; }
16 } /* ApplicationName */
17
18 private EventLog Log {
19 get { return this._Log; }
20 } /* Log */
21
22 public EventLogger(string applicationName) {
23 this._ApplicationName = applicationName;
24 this._Log = new EventLog();
25 this.Log.Source = this.ApplicationName;
26 } /* EventLogger */
27 } /* EventLogger */
28} /* CumpsD.Tools */
Let's create our first test. We want to read an EventLog.
1[Test]

2[ExpectedException(typeof(InvalidEventLogException))]
3public void ReadLog1() {
4 EventLogEntry[] EventLogs = this._ErrorLog.ReadLog(this._BadLog);
5}
We mark our method with the Test attribute, along with the ExcpectedException, because this._BadLog contains a non-existant logfile, and we want our class to throw an exception when trying that.

This test fails, because the ReadLog method doesn't exist yet. Let's create it, this requires some more coding, we'll have some private helper methods. SetLog to specify the EventLog we want to read from, and IsLog to check if the EventLog actually exists.
1private bool IsLog(string logName) {

2 return EventLog.Exists(logName);
3} /* IsLog */
4
5private void SetLog(string logName) {
6 if (this.IsLog(logName)) {
7 this._Log.Log = logName;
8 } else {
9 throw new InvalidEventLogException("Invalid Logfile.");
10 }
11} /* SetLog */
12
13public EventLogEntry[] ReadLog(string logName) {
14 this.SetLog(logName);
15 EventLogEntry[] EventLogs = new EventLogEntry[this.Log.Entries.Count];
16 this.Log.Entries.CopyTo(EventLogs, 0);
17 return EventLogs;
18} /* ReadLog */
This code on it's own will still fail, because there is no InvalidEventLogException! Let's add a class in the same file defining the Exception.
1[Serializable()]

2public class InvalidEventLogException: Exception, ISerializable {
3 public InvalidEventLogException(): base() { }
4
5 public InvalidEventLogException(string message): base(message) { }
6
7 public InvalidEventLogException(string message, Exception innerException): base (message, innerException) { }
8
9 protected InvalidEventLogException(SerializationInfo info, StreamingContext context): base(info, context) { }
10
11 [SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
12 public new void GetObjectData(SerializationInfo info, StreamingContext context) {
13 base.GetObjectData(info, context);
14 }
15} /* InvalidEventLogException */
When we run our test now, the EventLogger will throw an Exception and our test will pass, because we were expecting an exception.

Write a test with a valid EventLog name as well, and make it pass, the code shown above will work.

We also want a WriteLog method, to actually log our errors, so let's make a test for that.
1[Test]

2[ExpectedException(typeof(InvalidEventLogException))]
3public void WriteLog1() {
4 this._ErrorLog.WriteLog(this._BadLog, "This is a test entry");
5}
6
7[Test]
8public void WriteLog2() {
9 string ErrorMessage = this._ErrorLog.WriteLog(this._GoodLog, "I have encountered a catastrophic error!");
10 EventLogEntry[] EventLogs = this._ErrorLog.ReadLog(this._GoodLog);
11 Assert.AreEqual(ErrorMessage, EventLogs[EventLogs.Length-1].Message, "Wrong Error.");
12}
The WriteLog1 method is similar to the ReadLog1 method, it tries to write to an invalid EventLog and will fail. The WriteLog2 method however tries to write to a valid EventLog , and checks if the error is actually written afterwards.

Both tests will fail, because we'll write the methods now.

I have created an enum for the three types of EventLogEntries, Information , Warning and Error. Along with an overload for WriteLog so it would write an Error by default.
1public enum ErrorType { Information, Warning, Error }

2
3public string WriteLog(string logName, string errorMessage) {
4 return this.WriteLog(logName, errorMessage, ErrorType.Error);
5} /* WriteLog */
Our real WriteLog method will check for a valid EventLog and then write the Entry to the EventLog and return the error message it has written, so we can compare in our test.
1public string WriteLog(string logName, string errorMessage, ErrorType errorType) {

2 this.SetLog(logName);
3 EventLogEntryType LogType;
4 switch (errorType) {
5 case ErrorType.Information: LogType = EventLogEntryType.Information; break;
6 case ErrorType.Warning: LogType = EventLogEntryType.Warning; break;
7 case ErrorType.Error: LogType = EventLogEntryType.Error; break;
8 default: LogType = EventLogEntryType.Error; break;
9 }
10 this.Log.WriteEntry(String.Format(CultureInfo.InvariantCulture, "{0} caused the following error:\n{1}", this.ApplicationName, errorMessage), LogType);
11 return String.Format(CultureInfo.InvariantCulture, "{0} caused the following error:\n{1}", this.ApplicationName, errorMessage);
12} /* WriteLog */
If we run our tests now, we'll see they succeed. I have added some more tests to check if the Entry type was written correctly.

At the end you should have something like this:



And when you check eventvwr.msc you will see something like:



As always, I've uploaded the sources so you can check them on your own.

No Comments