简体   繁体   English

写入事件日志时出错,阻止Windows服务启动?

[英]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 : 我使用以下代码在我的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");
}

After installing the service.msi, when i started the service it started and then stoped. 安装service.msi后,当我启动服务时,它启动然后停止。 Then i found the following error in EventViewer windows log section: 然后我在EventViewer Windows日志部分中发现以下错误:

Service cannot be started. 服务无法启动。 System.ArgumentException: Source property was not set before writing to the event log. 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)

If the source already exists it looks like you don't initialize eventLog1.Source. 如果源已存在,则看起来您没有初始化eventLog1.Source。

Suggest you move the initialization code to OnStart and out of the constructor. 建议您将初始化代码移动到OnStart并从构造函数中移出。

And move these two lines out of the if statement: 并将这两行移出if语句:

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

Try the following: 请尝试以下方法:

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

Also put the following in OnStart: 还在OnStart中添加以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM