However, recently I've come across a mild annoyance. The standard .NET event log listener logs everything as info... great!
Luckily the .NET framework provides the ability to write your own custom trace listeners, so I decided to write my own. I have included the code for this trace listener below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace aCompany.Diagnostics
{
public class EventLogListener: TraceListener
{
#region Field(s)
private EventLog _eventLog;
#endregion
#region Constructor(s)
public EventLogListener(string sourceName)
{
_eventLog = new EventLog();
_eventLog.Source = sourceName;
}
#endregion
#region Public Method(s)
public override void Write(string message)
{
_eventLog.WriteEntry(message, EventLogEntryType.Information);
}
public override void WriteLine(string message)
{
this.Write(message + Environment.NewLine);
}
public override void Fail(string message)
{
_eventLog.WriteEntry(message, EventLogEntryType.Error);
}
public override void Fail(string message, string detailMessage)
{
_eventLog.WriteEntry(message + Environment.NewLine + detailMessage, EventLogEntryType.Error);
}
public override void WriteLine(string message, string category)
{
EventLogEntryType entryType = (EventLogEntryType)Enum.Parse(typeof(EventLogEntryType), category);
_eventLog.WriteEntry(message, entryType);
}
#endregion
}
}
There is also a WriteLine() that takes a category as an argument. I have used this to represent a string of EventLogEntryType, so this can be used to created any type of event.
The event source that the events will be added to is passed in as an argument to the constructor.
Hope you find this useful.
No comments:
Post a Comment