簡體   English   中英

在Windows服務程序中記錄事件

[英]Logging Events in a Windows Service Program

我已經創建了一個Windows服務程序,我希望我的錯誤嚴格寫入Windows eventLog。 所以我從代碼項目文章中遵循了以下步驟:

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

但是,當我啟動或停止服務時,我沒有在事件查看器窗口中創建的事件日志中看到任何自定義日志消息。 另外,如何指定消息是由於錯誤還是僅僅是信息?

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

它實際上非常簡單。

我終於通過結合各種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");
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM