Friday, May 10, 2013

Create Custom Event log for your Project

You can log your custom events from your application/Project to Window Event Viewer. This is mainly used for Debug or Error/Exception handling.

How to create Event Logger ?


public class EventLogger
    {
        string SourceName;  // Source name of an evet receiver
        public EventLogger(string sourcename)
        {
            this.SourceName = sourcename;
        }

        public void WriteToEventLog(string message)
        {
            EventLog elog = new EventLog();

            if (!EventLog.SourceExists(SourceName))
            {
                EventLog.CreateEventSource(SourceName, SourceName);
            }

            elog.Source = SourceName;
            elog.EnableRaisingEvents = true;
            elog.WriteEntry(message);
        }

    }

How to Use it ?

EventLogger eventlog = new EventLogger("MyEventLog");
eventlog.WriteToEventLog("Testing My Event Log!!!");

Where to find our log ?

Start --> Type "EventViewer" --> expand "Applications and Services Logs" and click your EventLog (By SourceName which you gave in the EventLogger Constructor)

How to delete the source from Event Viewer?

[HKEY_LOCAL_MACHINE] --> SYSTEM --> CurrentControlSet --> Services --> Eventlog then select your Event Logger then right click and delete it.