Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在Windows服务程序中记录事件_C#_Events_Service_Logging - Fatal编程技术网

C# 在Windows服务程序中记录事件

C# 在Windows服务程序中记录事件,c#,events,service,logging,C#,Events,Service,Logging,我已经创建了一个Windows服务程序,我希望我的错误严格写入Windows事件日志。因此,我遵循了代码项目文章中的以下步骤: 但是,在启动或停止服务时,我在“事件查看器”窗口中创建的事件日志中没有看到任何自定义日志消息。 另外,我如何指定该消息是由于错误还是仅仅是信息?首先,是您的朋友。确保你检查了链接,因为有一些潜在的陷阱值得知道 基本上,您可以创建一个EventLog对象: this.ServiceName = "MyService"; this.EventLog = new Syste

我已经创建了一个Windows服务程序,我希望我的错误严格写入Windows事件日志。因此,我遵循了代码项目文章中的以下步骤:

但是,在启动或停止服务时,我在“事件查看器”窗口中创建的事件日志中没有看到任何自定义日志消息。 另外,我如何指定该消息是由于错误还是仅仅是信息?

首先,是您的朋友。确保你检查了链接,因为有一些潜在的陷阱值得知道

基本上,您可以创建一个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");
    }

请注意,您需要具有正确的权限才能实际创建日志。否则,您肯定会遇到异常(至少从Windows Server 2003开始),这在MSDN文档中有明确说明。@alphadogg ServiceBase的EventLog属性是只读的。代码是错误的。默认情况下,基于.NET的Windows服务将以“应用程序”的形式写入事件日志,因此您不需要手动指定它。请您解释一下为什么在代码中使用
ISupportInitialize
?也就是说,为什么需要将代码封装在BeginInit()/EndInit()对中?谢谢。有人知道我们在哪里可以找到/查看此日志吗?