在Windows服务程序中记录事件

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)

它实际上非常简单.

  • 请注意,您需要具有实际创建日志的正确权限.否则你会得到一个例外(至少从Windows Server 2003开始) (10认同)
  • @alphadogg ServiceBase的EventLog属性是readonly.代码错了.默认情况下,基于.NET的Windows服务会将事件日志写为"应用程序",因此您无需手动指定它. (9认同)
  • 你能解释为什么在你的代码中使用`ISupportInitialize`吗?也就是说,为什么需要将代码括在BeginInit()/ EndInit()对中?谢谢. (3认同)

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)