2010-11-23 118 views
7

我使用下面的代碼在我Windows服務應用程序創建自定義事件日誌寫入事件日誌時出錯,阻止啓動Windows服務?

public ServiceConstructor() 
{ 
    InitializeComponent(); 
    if (!EventLog.SourceExists("WinService")) 
    { 
    EventLog.CreateEventSource("WinService", "WinServiceLog"); 
    eventLog1.Source = "WinService"; 
    eventLog1.Log = "WinServiceLog"; 
    } 
} 
protected override void OnStart(string[] args) 
{ 
eventLog1.WriteEntry("Started"); 
} 

安裝service.msi,當我開始就開始服務,然後採空後。然後我在EventViewer窗口日誌部分發現以下錯誤:

服務無法啓動。 System.ArgumentException:在將 寫入事件日誌之前未設置Source屬性。

at System.Diagnostics.EventLog.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData) at System.Diagnostics.EventLog.WriteEntry(String message) at WinService.Service.OnStart(String[] args) at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)

回答

6

如果源已經存在,它看起來像你沒有初始化eventLog1.Source。

建議您將初始化代碼移到OnStart並從構造函數中移出。

並移動這兩條線出來的IF語句:

eventLog1.Source = "WinService"; 
eventLog1.Log = "WinServiceLog"; 
4

嘗試以下操作:

EventLog.CreateEventSource("WinService", "Application");
eventLog1.Log = "Application";

也把處理通信以下:

eventLog1.Log="Application"
eventLog1.Source = "WinService";

相關問題