Wednesday, 12 October 2011

How to register Window Eventlog sources.

The issue:
I use the following code to register a windows eventlog source in code. It worked in the dev environment but not in UAT or PROD

// Create the source, if it does not already exist.
if(!EventLog.SourceExists("MySource"))
{
//An event log source should not be created and immediately used.
//There is a latency time to enable the source, it should be created
//prior to executing the application that uses the source.
//Execute this sample a second time to use the new source.
EventLog.CreateEventSource("MySource", "MyNewLog");
Console.WriteLine("CreatedEventSource");
Console.WriteLine("Exiting, execute the application a second time to use the source.");
// The source is created.  Exit the application to allow it to be registered.
return;
}

// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource";

// Write an informational entry to the event log.    
myLog.WriteEntry("Writing to event log.");

The Cause:
Permission! The app is run as a scheduled task. It turns out the account the app is running under is no enough for creating a eventlog source. And windows keeps silent about it.

The Solution:
You can add a eventlog source directly into the registry. Best of all when you deploy, you can just export and import the registry.
HKEY_LOCAL_MACHINE
SYSTEM
CurrentControlSet
Services
Eventlog

http://msdn.microsoft.com/en-us/library/windows/desktop/aa363648(v=vs.85).aspx

No comments:

Post a Comment