我在C#控制台应用程序和C#windows服务中都有以下代码。它在控制台应用程序中工作。它拾取指定的事件,并正确调用MatchEvent()。C#windows服务中的同一代码不会拾取相同的指定事件,它不会看到它,而是看到其他事件。有问题的事件已写入应用程序日志,因此我不尝试读取安全日志。
我有什么遗漏吗?我也研究了EventLogPermission,但这似乎不适用,因为我正在从eventLog中获取事件。
守则:
private void WatchLogs()
{
try
{
_eventLogs = EventLog.GetEventLogs();
foreach (EventLog eventLog in _eventLogs)
{
if (eventLog.LogDisplayName.Contains("Security"))
{
_logger.DebugFormat(string.Format("{0}: not watching", eventLog.LogDisplayName));
}
else
{
eventLog.EntryWritten += EventLogEntryWritten;
eventLog.EnableRaisingEvents = true;
if (_logger.IsInfoEnabled)
{
_logger.InfoFormat("Monitoring: {0} | Raising Events: {1}", eventLog.LogDisplayName,
eventLog.EnableRaisingEvents);
}
}
}
}
catch (Win32Exception ee)
{
_logger.DebugFormat(string.Format("{0}: not watching({1})", eventLog.LogDisplayName, ee.Message));
}
catch (SecurityException securityException)
{
_logger.ErrorFormat("Error accessing eventlog: {0} : {1}", eventLog.LogDisplayName, securityException.Message);
}
}
private void EventLogEntryWritten(object sender, EntryWrittenEventArgs currentEvent)
{
var log = (EventLog) sender;
if (_logger.IsDebugEnabled)
_logger.DebugFormat(
"Event Raised: |Log:{0}|Source:{1}|EventID:{2}|",log.LogDisplayName,
currentEvent.Entry.Source,currentEvent.Entry.EventID);
MatchEvent(currentEvent);
}