写入事件日志时出错,导致 Windows 服务无法启动?

发布于 2024-10-03 13:15:05 字数 883 浏览 0 评论 0原文

我使用以下代码在我的 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:写入前未设置源属性 到事件日志。

at System.Diagnostics.EventLog.WriteEntry(字符串消息,EventLogEntryType 类型,Int32 事件ID,Int16 类别,Byte[] rawData) 在 System.Diagnostics.EventLog.WriteEntry(字符串消息) 在 WinService.Service.OnStart(String[] args) 在System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(对象状态)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

篱下浅笙歌 2024-10-10 13:15:18

请尝试以下操作:

EventLog.CreateEventSource("WinService", "Application");


eventLog1.Log = "Application";

还将以下内容放入 OnStart 中:

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

Try the following:

EventLog.CreateEventSource("WinService", "Application");

and
eventLog1.Log = "Application";

Also put the following in OnStart:

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

如果源已经存在,则看起来您没有初始化 eventLog1.Source。

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

并将这两行移出 if 语句:

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

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";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文