Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while writing to event log, prevents windows service from starting?

I am using the following code to create a custom event log in my windows service application:

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");
}

After installing the service.msi, when i started the service it started and then stoped. Then i found the following error in EventViewer windows log section:

Service cannot be started. System.ArgumentException: Source property was not set before writing to the event log.

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)

like image 894
Harun Avatar asked Nov 23 '10 06:11

Harun


2 Answers

Try the following:

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

Also put the following in OnStart:

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

like image 79
basarat Avatar answered Oct 31 '22 08:10

basarat


If the source already exists it looks like you don't initialize eventLog1.Source.

Suggest you move the initialization code to OnStart and out of the constructor.

And move these two lines out of the if statement:

eventLog1.Source = "WinService";
eventLog1.Log = "WinServiceLog";
like image 12
Ian Mercer Avatar answered Oct 31 '22 08:10

Ian Mercer