【问题标题】:Logging Events in a Windows Service Program在 Windows 服务程序中记录事件
【发布时间】:2011-12-30 21:50:21
【问题描述】:

我创建了一个 Windows 服务程序,我希望将我的错误严格写入 Windows 事件日志。所以我按照代码项目文章中的这些步骤操作:

http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

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

【问题讨论】:

    标签: c# events service logging


    【解决方案1】:

    我终于通过结合各种 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");
        }
    

    【讨论】:

      【解决方案2】:

      首先,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);
      

      其实很简单。

      【讨论】:

      • 请注意,您需要拥有正确的权限才能实际创建日志。否则你会得到一个异常(至少从 Windows Server 2003 开始​​)
      • 当然,这在 MSDN 文档中有明确说明。
      • @alphadogg ServiceBase 的 EventLog 属性是只读的。代码是错误的。默认情况下,基于 .NET 的 Windows 服务会将事件日志写入“应用程序”,因此您无需手动指定。
      • 您能否解释一下为什么在您的代码中使用ISupportInitialize?也就是说,为什么需要将代码包含在 BeginInit()/EndInit() 对中?谢谢。
      • 有人知道我们在哪里可以找到/查看此日志吗?
      猜你喜欢
      • 1970-01-01
      • 2016-01-13
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多