2012-01-06 68 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"; 
相關問題