Wednesday, October 30, 2013

Logging errors to Windows Event Log

A windows service, gets added to the list of services and gets executed automatically, hence we need a good set of logs to identify issues with the service. We shall see on how to write appropriate logs into the Windows event log for each action performed in the Windows service.

We shall add a new utility class LogHelper which will log the events to the Windows Event Log and call the methods in this helper class to log the status of the windows service.

Add a new class called LogHelper.cs and add the following logging methods to the class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NotificationService
{
    static class LogHelper
    {
        private static System.Diagnostics.EventLog winEventLog;
        //
        public static void LogMessage(string logMessage, char logType)
        {
            // Check for the existance of the Custom Event source, if not create a new SOurce
            if (!System.Diagnostics.EventLog.SourceExists("NotificationService"))
            {
                System.Diagnostics.EventLog.CreateEventSource("NotificationService", "Application");
            }
            //
            // Initialize the Log object
            winEventLog = new System.Diagnostics.EventLog("Application", Environment.MachineName, "NotificationService");
            //
            switch (logType)
            {
                case 'E':
                {
                    winEventLog.WriteEntry(logMessage, System.Diagnostics.EventLogEntryType.Error);
                    break;
                }
                case 'I':
                {
                    winEventLog.WriteEntry(logMessage, System.Diagnostics.EventLogEntryType.Information);
                    break;
                }
            }           
        }
    }
}

Now call the LogMessage method from the service appropriately to log errors and information to the Windows event log.

protected override void OnStart(string[] args)
{
    try
    {
        if (double.TryParse(ConfigurationManager.AppSettings["timer_interval"], out timer_interval))
        {
            serviceTimer = new Timer(timer_interval);
            serviceTimer.Elapsed += CheckErrorNotifications;
            serviceTimer.Start();
            LogHelper.LogMessage("Notification Service Started ...", 'I');
        }
        else
        {
            LogHelper.LogMessage("Unable to read the Service Interval.", 'E');
            //Conversion to Double failed, Log error here
        }
    }
    catch (Exception ex)
    {
        LogHelper.LogMessage("Unable to start Notification Service\n, Exception: " + ex.Message + "\n Stack Trace: " + ex.StackTrace, 'E');
    }
}
//
private void CheckErrorNotifications(object sender, ElapsedEventArgs args)
{
    LogHelper.LogMessage("Processing error messages, Started ...", 'I');
    //
    LogHelper.LogMessage("Processing error messages, Completed.", 'I');
}
//
protected override void OnStop()
{
    LogHelper.LogMessage("Notification Service Stopped.", 'I');
}


When the service starts, appropriate entries will be made to the windows event log as follows.




Search Flipkart Products:
Flipkart.com

No comments: