在 Windows 服务程序中记录事件 [英] Logging Events in a Windows Service Program

查看:22
本文介绍了在 Windows 服务程序中记录事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 Windows 服务程序,我希望我的错误严格写入 Windows eventLog.所以我按照代码项目文章中的这些步骤操作:

http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

但是当我启动或停止服务时,我没有看到我在事件查看器窗口中创建的事件日志中写入的任何自定义日志消息.另外我如何指定消息是由于错误还是只是信息?

解决方案

首先,MSDN 是你的朋友.请务必查看链接,因为有一些潜在的问题值得了解.

本质上,您创建了一个 EventLog 对象:

this.ServiceName = "MyService";this.EventLog = new System.Diagnostics.EventLog();this.EventLog.Source = this.ServiceName;this.EventLog.Log = "应用程序";

您还需要创建一个源,如果上述源不存在:

((ISupportInitialize)(this.EventLog)).BeginInit();如果 (!EventLog.SourceExists(this.EventLog.Source)){EventLog.CreateEventSource(this.EventLog.Source, this.EventLog.Log);}((ISupportInitialize)(this.EventLog)).EndInit();

然后简单地使用它:

this.EventLog.WriteEntry("我的事件日志消息.", EventLogEntryType.Information);

其实很简单.

I have created a Windows service program and I want my error to strictly be written to the Windows eventLog. So I followed these steps from code project article:

http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

But I don't see any of the custom log messages I wrote in the event logs created in the event viewer window when I start or stop the service. Also how do I specify whether the message was due to an error or is just info?

解决方案

First, MSDN is your friend. Make sure you check out the link, as there are some potential gotchas worth knowing.

Essentially, you create an EventLog object:

this.ServiceName = "MyService";
this.EventLog = new System.Diagnostics.EventLog();
this.EventLog.Source = this.ServiceName;
this.EventLog.Log = "Application";

You also need to create a source, if the above source doesn't exist:

((ISupportInitialize)(this.EventLog)).BeginInit();
if (!EventLog.SourceExists(this.EventLog.Source))
{
    EventLog.CreateEventSource(this.EventLog.Source, this.EventLog.Log);
}
((ISupportInitialize)(this.EventLog)).EndInit();

and then simply use it:

this.EventLog.WriteEntry("My Eventlog message.", EventLogEntryType.Information);

it's actually pretty simple.

这篇关于在 Windows 服务程序中记录事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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