2012-01-06 71 views
1

我创建了Windows服务。我创建了一个事件日志。如何使用C#创建自定义事件日志

public Service1() 
{ 
     InitializeComponent(); 
     this.ServiceName = ConfigurationManager.AppSettings.Get("ServiceName"); 

     string sourceName = ConfigurationManager.AppSettings.Get("ServiceName"); 
     string logName = ConfigurationManager.AppSettings["EventLogName"]; 
     try 
     { 
      if (!System.Diagnostics.EventLog.Exists(sourceName)) 
       System.Diagnostics.EventLog.CreateEventSource(sourceName, logName); 
      eventLog.Source = sourceName; 
      eventLog.Log = logName; 
     } 
     catch 
     { 
      eventLog.Source = "Application"; 
     } 
    } 

在初始化过程中,服务已安装并且未创建日志。日志条目位于系统的Application日志中。

我错过了什么?

我使用过程中的安装程序安装

public ProjectInstaller() 
{ 
     InitializeComponent(); 
     this.Installers.Add(GetServiceInstaller()); 
     this.Installers.Add(GetServiceProcessInstaller()); 
} 

private ServiceInstaller GetServiceInstaller() 
{ 
     serviceInstaller.ServiceName = GetConfigurationValue("ServiceName"); 
     serviceInstaller.Description = GetConfigurationValue("Description"); 
     serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; 
     return serviceInstaller; 
} 

private ServiceProcessInstaller GetServiceProcessInstaller() 
{ 
     serviceProcessinstaller.Account = ServiceAccount.LocalSystem; 
     return serviceProcessinstaller; 
} 

如何创建事件日志?

回答

2

更改您的代码如下:

if (!System.Diagnostics.EventLog.SourceExists(sourceName)) 
      System.Diagnostics.EventLog.CreateEventSource(sourceName, logName); 
+1

我想你的代码。但它没有创建事件日志并且无法启动该服务。该服务显示服务无法启动。 System.ArgumentException:源'SyncronizationService'未在日志'SyncronizationLog'中注册。 (它在日志'Application'中注册。)“Source和Log属性必须匹配,或者您可以将Log设置为空字符串,并且它会自动匹配到Source属性。错误消息 – Pooja 2012-01-06 07:44:49

+1

请注意,logName必须有独特的第一个字符,请检查此链接http://msdn.microsoft.com/en-us/library/y7x55536%28v=vs.90%29.aspx – Mhmd 2012-05-16 17:06:42

0

尝试AUTOLOG设置为false第一。

this.AutoLog = false; 

    if (!System.Diagnostics.EventLog.SourceExists(sourceName)) 
    {   
     System.Diagnostics.EventLog.CreateEventSource(sourceName, logName); 
    } 

    eventLog.Source = "MySource"; 

在此MSDN walkthrough,他们似乎完全省略了该步骤。然而,在这个MSDN“How to:”他们陈述:

如果你想写比应用程序日志等事件日志,您必须设置AUTOLOG属性设置为false,你的服务中创建自己的自定义事件日志代码,并将您的服务注册为该日志的有效条目来源。

将自动日志设置为false后,我的自定义日志和事件显示为预期。

0

ServiceName和Source必须是不同的名称。

服务名称

this.serviceInstaller1.ServiceName = "MaliyeWMService"; 

来源

if (!System.Diagnostics.EventLog.SourceExists("MaliyeMailService")) 
{ 
    System.Diagnostics.EventLog.CreateEventSource("MaliyeMailService", "MaliyeMailServiceLog"); 

} 
OlayLog.Source = "MaliyeMailService"; 
相关问题