如何使用C#写入Windows Server 2008中的eventlog?

时间:2010-10-02 12:18:45

标签: c# .net windows-server-2008-r2

我有以下代码在Windows Server 2003中运行良好。它会写入EventViewer中的应用程序事件日志。相同的代码在Windows 2008中不起作用。应用程序崩溃。请求获取有关如何在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 个答案:

答案 0 :(得分:4)

您需要成为本地Administrators组的成员才能创建新的事件源。源可能存在于Server 2003上,或者您已具有该操作系统所需的权限。在Server 2008上,即使您是管理员,默认也是在没有提升权限的情况下运行。在这种情况下,您必须右键单击您的应用程序并选择“以管理员身份运行”。

答案 1 :(得分:2)

它与Windows 2008中的新权限集有关,并且您的帐户没有特权访问权限来创建新的事件日志源。

为应用程序创建安装程序时,最好是创建这些事件日志源,因为通常您必须运行具有特权的安装程序。

答案 2 :(得分:0)

重新'应用程序崩溃' - 这不应该发生在托管环境中。也许在这种情况下它与权限相关,但是你将永远处于黑暗中并重新启动你的应用程序,除非你添加逻辑来处理错误(例外)。

将此更改为

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

并查看Exception类和字段(例如e.Messagee.StrackTrace),您可以确定哪些错误以及发生的位置。