写入事件日志时出错,阻止Windows服务启动? [英] Error while writing to event log, prevents windows service from starting?

查看:107
本文介绍了写入事件日志时出错,阻止Windows服务启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码在我的 windows服务应用程序中创建自定义事件日志:

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

安装service.msi后,当我启动该服务时,它先启动然后停止.然后我在EventViewer Windows日志部分中发现以下错误:

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:

服务无法启动. System.ArgumentException:写入之前未设置Source属性 进入事件日志.

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)

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)

推荐答案

如果源已经存在,则好像您没有初始化eventLog1.Source.

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

建议您将初始化代码移至OnStart并移出构造函数.

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

并将这两行移出if语句:

And move these two lines out of the if statement:

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

这篇关于写入事件日志时出错,阻止Windows服务启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆