【发布时间】:2011-12-30 21:50:21
【问题描述】:
我创建了一个 Windows 服务程序,我希望将我的错误严格写入 Windows 事件日志。所以我按照代码项目文章中的这些步骤操作:
http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx
但是当我启动或停止服务时,我在事件查看器窗口中创建的事件日志中没有看到任何自定义日志消息。 另外,我如何指定消息是由于错误还是只是信息?
【问题讨论】:
我创建了一个 Windows 服务程序,我希望将我的错误严格写入 Windows 事件日志。所以我按照代码项目文章中的这些步骤操作:
http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx
但是当我启动或停止服务时,我在事件查看器窗口中创建的事件日志中没有看到任何自定义日志消息。 另外,我如何指定消息是由于错误还是只是信息?
【问题讨论】:
我终于通过结合各种 StackOverflow 答案和来自 MSDN 的方法来实现这一点。
首先包含以下命名空间
using System.ComponentModel;
using System.Diagnostics;
然后在您的构造函数中设置日志记录
public UserService1()
{
//Setup Service
this.ServiceName = "MyService2";
this.CanStop = true;
this.CanPauseAndContinue = true;
//Setup logging
this.AutoLog = false;
((ISupportInitialize) this.EventLog).BeginInit();
if (!EventLog.SourceExists(this.ServiceName))
{
EventLog.CreateEventSource(this.ServiceName, "Application");
}
((ISupportInitialize) this.EventLog).EndInit();
this.EventLog.Source = this.ServiceName;
this.EventLog.Log = "Application";
}
如下使用:
protected override void OnStart(string[] args)
{
base.OnStart(args);
this.EventLog.WriteEntry("In OnStart");
}
【讨论】:
首先,MSDN 是你的朋友。请务必查看链接,因为有一些潜在的陷阱值得了解。
本质上,您创建了一个 EventLog 对象:
this.ServiceName = "MyService";
this.EventLog = new System.Diagnostics.EventLog();
this.EventLog.Source = this.ServiceName;
this.EventLog.Log = "Application";
如果上述源不存在,您还需要创建一个源:
((ISupportInitialize)(this.EventLog)).BeginInit();
if (!EventLog.SourceExists(this.EventLog.Source))
{
EventLog.CreateEventSource(this.EventLog.Source, this.EventLog.Log);
}
((ISupportInitialize)(this.EventLog)).EndInit();
然后简单地使用它:
this.EventLog.WriteEntry("My Eventlog message.", EventLogEntryType.Information);
其实很简单。
【讨论】:
ISupportInitialize?也就是说,为什么需要将代码包含在 BeginInit()/EndInit() 对中?谢谢。