[英]Logging Events in a Windows Service Program
我已经创建了一个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 = "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);
它实际上非常简单。
我终于通过结合各种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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.