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);
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".
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.
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.
精彩评论