1

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);

3 Answers 3

4

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".

3
  • Thanks i ran my application in administrator mode. Now its working fine.
    – Defendore
    Oct 4, 2010 at 8:35
  • So what if my console app is intended to run as a Windows service?How do I elevate the rights of the service on startup?
    – Maltrap
    Nov 30, 2012 at 0:22
  • 1
    @Maltrap: Services do not "elevate" (there is no user to answer the UAC prompt). When you install a service you configure it to run with a specific user account. You can see the user in the properties dialog box for the service. If you want to let this user create an event source it has to have the right privileges. However, the proper and secure solution is to let the installer not only install the service but also the required event sources. Then the service user does not need excess privileges and when you uninstall the service the system is cleaned up. Nov 30, 2012 at 7:12
2

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.

0
0

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.