Reputation: 12900
I am writing a simple service and logging exceptions and other notable items to the EventLog. Below is the code for the service. Somehow, although I can see the "FDaemon" log, I don't see any events in it. My started and stopped events are nowhere in the log; the log lists 0 events.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
namespace FDaemon
{
public class EmailDigester : ServiceBase, IDebuggableService
{
private Timer digestTimer;
private EmailDigesterWorker worker;
private EventLog eventLog;
public EmailDigester()
{
// fire up the event log
this.eventLog = new System.Diagnostics.EventLog();
((ISupportInitialize)(this.eventLog)).BeginInit();
this.eventLog.Source = "EmailDigester";
this.eventLog.Log = "FDaemon";
if (!EventLog.SourceExists(this.eventLog.Source))
{
EventLog.CreateEventSource(this.eventLog.Source, this.eventLog.Log);
}
this.AutoLog = false;
this.ServiceName = this.eventLog.Source;
((ISupportInitialize)(this.eventLog)).EndInit();
}
public void DebugStart(string[] args)
{
this.OnStart(args);
}
protected override void OnStart(string[] args)
{
this.worker = new EmailDigesterWorker(1, eventLog);
// no need to multithread, so use a simple Timer
// note: do not take more time in the callback delegate than the repetition interval
if (worker.RunTime.HasValue)
{
worker.ServiceStarted = true;
TimerCallback work = new TimerCallback(this.worker.ExecuteTask);
TimeSpan daily = new TimeSpan(24, 0, 0); // repeat every 24 hrs
TimeSpan startIn; // how much time till we start timer
if (worker.RunTime <= DateTime.Now)
startIn = (worker.RunTime.Value.AddDays(1.00) - DateTime.Now); // runTime is earlier than now. we missed, so add a day to runTime
else
startIn = (worker.RunTime.Value - DateTime.Now);
this.digestTimer = new Timer(work, null, startIn, daily);
}
eventLog.WriteEntry("EmailDigester started.", EventLogEntryType.Information);
}
public void DebugStop()
{
this.OnStop();
}
protected override void OnStop()
{
worker.ServiceStarted = false;
if (this.digestTimer != null)
{
this.digestTimer.Dispose();
}
eventLog.WriteEntry("EmailDigester stopped.", EventLogEntryType.Information);
}
}
}
Upvotes: 3
Views: 8674
Reputation: 2866
First: I am assuming that you've stepped through and the WriteEntry()
function does, in fact, execute.
If your source "EmailDigester"
is registered with any other EventLogs
(e.g. Application, Security, etc.), then the messages will appear in that EventLog
no matter what you do. In fact, I believe only the first 8 characters of a source are considered.
You can check this by going to the registry @:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\
and checking each log's sources.
You might also considering changing your source to a random value (that you know won't be registered) and seeing if your logs show up.
Upvotes: 4