Monday, February 16, 2009

Helper Class For Event Logging, C#


public class LoggingHelper
{
public enum LoggingType
{
File, EventLog
}

public enum EventType
{
Error, Information, Warning
}

private string strLoggingFilePath, strEventLogCategoryName;


LoggingType objLogType;
///


/// Logging class constructor to initialize the logging process
///

/// Logging can be in File or in the EventLog
/// If the selected type is File then Name will be the File Path,
/// if the selected type is the Event log then Name will be the Event Category Name

public LoggingHelper(LoggingType LogType, string Name)
{
objLogType = LogType;
switch (LogType)
{
case (LoggingType.EventLog):
strEventLogCategoryName = Name;
if (!System.Diagnostics.EventLog.SourceExists(Name))
{
System.Diagnostics.EventLog.CreateEventSource(Name, Name);
}

break;
case (LoggingType.File):
strLoggingFilePath = Name;
if (!Directory.Exists(Path.GetDirectoryName(strLoggingFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(strLoggingFilePath));
}
break;
}
}
public void LogEvent(string Event, EventType Type)
{
StreamWriter EventWriter;
if (objLogType == LoggingType.EventLog)
{
EventLog.WriteEntry(strEventLogCategoryName, Event, Type == EventType.Error ? EventLogEntryType.Error : Type == EventType.Information ? EventLogEntryType.Information : Type == EventType.Warning ? EventLogEntryType.Warning : EventLogEntryType.SuccessAudit);
}
else if (objLogType == LoggingType.File)
{
if (!File.Exists(strLoggingFilePath))
{
EventWriter = new StreamWriter(strLoggingFilePath, false);
}
else
{
EventWriter = new StreamWriter(strLoggingFilePath, true);
}
EventWriter.WriteLine(DateTime.Now.ToString() + "/t" +
Event, Type == EventType.Error ? "Error" : Type == EventType.Information ? "Information" : Type == EventType.Warning ? "Warning" : ""
+ "/t" + Event);
}
}

No comments:

Post a Comment