Defendore
Defendore

Reputation: 649

How to write to eventlog in Windows Server 2008 using C#?

I have the following piece of code that works well in Windows Server 2003. It writes to the Application Event Log in EventViewer. The same code doesn't work in Windows 2008. The application crashes. Request to help on how to write to event log in Windows Server 2008.

if (!EventLog.SourceExists("MyServiceLog"))
{
    EventLog.CreateEventSource("MyServiceLog", "Application");
}
//Create an EventLog instance and assign its source.
EventLog eventLog = new EventLog();
eventLog.Source = "MyServiceLog";
//Write an informational entry to the event log.
eventLog.WriteEntry(Header + ": " + FailureReason);

Upvotes: 1

Views: 7204

Answers (3)

Steve Townsend
Steve Townsend

Reputation: 54178

re 'the application crashes' - this should not happen in managed environment. Maybe in this case it's permissions-related, but you will be forever in the dark and restarting your app unless you add logic to handle errors (i.e. exceptions).

Change this to

try 
{ 
    /* put your event log code here */ 
} 
catch (Exception e) 
{ 
    /* new code to gracefully handle errors */ 
}

and look at the Exception class and fields (such as e.Message, e.StrackTrace) that you are getting to work out exactly what's wrong and where it happened.

Upvotes: 0

Martin
Martin

Reputation: 119

It has to do with the new permission sets in Windows 2008 and your account doesn't have the privileged access to create new event log sources.

When you create an installer for your application, best will be to create those event log sources then, because normally you have to run the installers with privileged rights.

Upvotes: 2

Martin Liversage
Martin Liversage

Reputation: 106936

You need to be member of the local Administrators group in order to create a new event source. The source probably exists on Server 2003 or you already have the required permissions on that operating system. On Server 2008 the default is to run without elevated privileges even though you are an administrator. In that case you will have to right click your application and select "Run as Administrator".

Upvotes: 4

Related Questions