Translate

Thursday, May 24, 2012

Create a custom event log in Windows 7 using C# (Log error in event log c#)

What I am going to show you in this article is how to create a custom log for your windows based application.





















The console application C# code below was used to achieve the above


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace CreateEventLog
{
    class Program
    {
        static void Main(string[] args)
        {
            string source = "mySource";
            string logName = "myLog";
            CreateCustomEvent(source, logName);
            LogAnEventInTheCustomEvent(source);
            // DeleteCustomEvent(source, logName);//Use this if you want to delete this custom log
        }


        static void CreateCustomEvent(string source, string logName)
        {

            if (!EventLog.SourceExists(source))
            {
                EventLog.CreateEventSource(source, logName);

            }

        }

        static void LogAnEventInTheCustomEvent(string source)
        {
            // Create an EventLog instance and assign its source.
            EventLog myLog = new EventLog();
            myLog.Source = source;

            // Write an informational entry to the event log.    
            myLog.WriteEntry("myInformation", EventLogEntryType.Information);

            // Write an error entry to the event log.    
            myLog.WriteEntry("myError", EventLogEntryType.Error);

        }

        static void DeleteCustomEvent(string source, string logName)
        {
            if (EventLog.SourceExists(source))
            {
                EventLog.DeleteEventSource(source);
                EventLog.Delete(logName);
            }

        }
    }
}



Another way to delete the custom event log is to delete the
[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\Eventlog\myLog]
log folder in the registry



Note that by default the maximum size allotted to an event log is 512 KB. Once this limit is reached the older entries start getting over written by the newer entries.

To increase the maximum space allotted to a windows event log use the code below


EventLog myLog = new EventLog();
myLog.Source = "mySource";
myLog.MaximumKilobytes = 10048;


This code will increase the maximum size allotted to the event with the source mySource to 10,048 KB (ie 10 MB). After that limit is crossed, old events would start getting overwritten.

Further reading
http://msdn.microsoft.com/en-us/library/2awhba7a.aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.modifyoverflowpolicy(v=vs.110).aspx

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator