简体   繁体   English

在Windows服务程序中记录事件

[英]Logging Events in a Windows Service Program

I have created a Windows service program and I want my error to strictly be written to the Windows eventLog. 我已经创建了一个Windows服务程序,我希望我的错误严格写入Windows eventLog。 So I followed these steps from code project article: 所以我从代码项目文章中遵循了以下步骤:

http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx 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. 首先, MSDN是你的朋友。 Make sure you check out the link, as there are some potential gotchas worth knowing. 请务必查看链接,因为有一些潜在的问题值得了解。

Essentially, you create an EventLog object: 基本上,您创建一个EventLog对象:

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. 它实际上非常简单。

I finally got this to work by combining various StackOverflow answers and from MSDN. 我终于通过结合各种StackOverflow答案和MSDN来实现这一点。

First include the following namespaces 首先包括以下命名空间

using System.ComponentModel;
using System.Diagnostics;

Then setup logging in your constructor 然后在构造函数中设置日志记录

    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";
    }

Use as follows: 使用方法如下:

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);

        this.EventLog.WriteEntry("In OnStart");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM