Arm*_*enB 39 c# service events logging
我创建了一个Windows服务程序,我希望我的错误严格写入Windows eventLog.所以我从代码项目文章中遵循了以下步骤:
http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx
但是,当我启动或停止服务时,我没有在事件查看器窗口中创建的事件日志中看到任何自定义日志消息.另外,如何指定消息是由于错误还是仅仅是信息?
alp*_*ogg 65
首先,MSDN是你的朋友.请务必查看链接,因为有一些潜在的问题值得了解.
基本上,您创建一个EventLog对象:
this.ServiceName = "MyService";
this.EventLog = new System.Diagnostics.EventLog();
this.EventLog.Source = this.ServiceName;
this.EventLog.Log = "Application";
Run Code Online (Sandbox Code Playgroud)
如果上述源不存在,您还需要创建源:
((ISupportInitialize)(this.EventLog)).BeginInit();
if (!EventLog.SourceExists(this.EventLog.Source))
{
EventLog.CreateEventSource(this.EventLog.Source, this.EventLog.Log);
}
((ISupportInitialize)(this.EventLog)).EndInit();
Run Code Online (Sandbox Code Playgroud)
然后简单地使用它:
this.EventLog.WriteEntry("My Eventlog message.", EventLogEntryType.Information);
Run Code Online (Sandbox Code Playgroud)
它实际上非常简单.
Jam*_*ate 26
我终于通过结合各种StackOverflow答案和MSDN来实现这一点.
首先包括以下命名空间
using System.ComponentModel;
using System.Diagnostics;
Run Code Online (Sandbox Code Playgroud)
然后在构造函数中设置日志记录
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";
}
Run Code Online (Sandbox Code Playgroud)
使用方法如下:
protected override void OnStart(string[] args)
{
base.OnStart(args);
this.EventLog.WriteEntry("In OnStart");
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
82843 次 |
最近记录: |