我正在编写一个简单的服务并将异常和其他值得注意的项目记录到 EventLog。下面是服务的代码。不知何故,虽然我可以看到“FDaemon”日志,但我没有在其中看到任何事件。我开始和停止的事件在日志中无处可见;日志列出了 0 个事件。
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);
}
}
}
最佳答案
第一:我假设您已经逐步完成并且 WriteEntry()
函数实际上确实执行了。
如果您的源 "EmailDigester"
注册了任何其他 EventLogs
(例如应用程序、安全性等),那么无论您做什么,消息都会出现在该 EventLog
中。实际上,我相信只考虑源的前 8 个字符 。
您可以通过转到注册表@进行检查:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\
并检查每个日志的来源。
您可能还考虑将源更改为随机值(您知道不会注册)并查看您的日志是否显示。
关于c# - 为什么 WriteEntry 不适用于此 EventLog 源?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7116705/