Logging Events in a Windows Service Program

2019-03-08 13:25发布

问题:

I have created a Windows service program and I want my error to strictly be written to the Windows eventLog. So I followed these steps from code project article:

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?

回答1:

First, MSDN is your friend. Make sure you check out the link, as there are some potential gotchas worth knowing.

Essentially, you create an EventLog object:

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.



回答2:

I finally got this to work by combining various StackOverflow answers and from 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");
    }