2011-11-16 52 views
34

我已经创建了一个Windows服务程序,并且我希望将我的错误严格写入Windows事件日志。所以我也跟着从代码项目文章下列步骤操作:在Windows服务程序中记录事件

http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

但我看不出有什么我在事件查看器窗口中创建事件日志编写的自定义日志消息时,我开始或停止服务。 另外,如何指定消息是由于错误还是仅仅是信息?

回答

57

首先,MSDN是你的朋友。确保你检查链接,因为有一些潜在的问题值得了解。

从本质上讲,创建一个事件日志对象:

this.ServiceName = "MyService"; 
this.EventLog = new System.Diagnostics.EventLog(); 
this.EventLog.Source = this.ServiceName; 
this.EventLog.Log = "Application"; 

您还需要创建一个源,如果上面的源代码不存在:

((ISupportInitialize)(this.EventLog)).BeginInit(); 
if (!EventLog.SourceExists(this.EventLog.Source)) 
{ 
    EventLog.CreateEventSource(this.EventLog.Source, this.EventLog.Log); 
} 
((ISupportInitialize)(this.EventLog)).EndInit(); 

,然后简单地使用它:

this.EventLog.WriteEntry("My Eventlog message.", EventLogEntryType.Information); 

它其实很简单。

+10

请注意,您将需要有正确的权限实际创建日志。否则,你会得到一个异常(至少是Windows Server 2003) –

+1

当然,这在MSDN文档中有明确说明。 – alphadogg

+8

@alphadogg ServiceBase的EventLog属性是只读的。代码是错误的。默认情况下,基于.NET的Windows Service会将事件日志写为“应用程序”,因此您无需手动指定它。 –

21

我终于通过结合各种StackOverflow答案和从MSDN得到这个工作。

首先包括以下命名空间

using System.ComponentModel; 
using System.Diagnostics; 

然后设置日志记录在你的构造

public UserService1() 
    { 
     //Setup Service 
     this.ServiceName = "MyService2"; 
     this.CanStop = true; 
     this.CanPauseAndContinue = true; 

     //Setup logging 
     this.AutoLog = false; 

     ((ISupportInitialize) this.EventLog).BeginInit(); 
     if (!EventLog.SourceExists(this.ServiceName)) 
     { 
      EventLog.CreateEventSource(this.ServiceName, "Application"); 
     } 
     ((ISupportInitialize) this.EventLog).EndInit(); 

     this.EventLog.Source = this.ServiceName; 
     this.EventLog.Log = "Application"; 
    } 

使用方法如下:

protected override void OnStart(string[] args) 
    { 
     base.OnStart(args); 

     this.EventLog.WriteEntry("In OnStart"); 
    }