GetNumberOfEventLogRecords returns 事件日志的数量不正确

GetNumberOfEventLogRecords returns incorrect number of event logs

我有这个 C++ 代码来读取事件日志记录

DWORD GetLogRecords(LPCWSTR wsLogFile)
{
  HANDLE hEvt = OpenEventLog(NULL, wsLogFile);
  if (hEvt==NULL) return 0;

  DWORD dwTotalRecords;
  BOOL res = GetNumberOfEventLogRecords(hEvt, &dwTotalRecords);
  CloseEventLog(hEvt);

  return (res != 0) ? dwTotalRecords : 0;
}

结果

atlTraceGeneral - C:\Windows\system32\winevt\logs\ACEEventLog.evtx - 23499 Total Records
atlTraceGeneral - C:\Windows\system32\winevt\logs\Application.evtx - 23499 Total Records
atlTraceGeneral - C:\Windows\system32\winevt\logs\ConnectionInfo.evtx - 23499 Total Records
atlTraceGeneral - C:\Windows\system32\winevt\logs\Error.evtx - 23499 Total Records
atlTraceGeneral - C:\Windows\system32\winevt\logs\HardwareEvents.evtx - 23499 Total Records
atlTraceGeneral - C:\Windows\system32\winevt\logs\Internet Explorer.evtx - 23499 Total Records
atlTraceGeneral - C:\Windows\system32\winevt\logs\Key Management Service.evtx - 23499 Total Records
 ...

我已使用计算机上所有 .EVTX 日志文件(150 个日志文件)的完整路径调用此函数。每次 returns 23499 !我的日志文件有不​​同的大小和一些 0,为什么我总是得到 23499?

更新 2:在我清除应用程序日志后,我现在所有 .evtx 日志文件都为 0。我认为它总是获取应用程序日志而不是指定的 .evtx 文件。

更新:正如 Remy Lebeau 所建议的那样,但结果仍然相同。

您没有检查 GetNumberOfEventLogRecords() 的结果是否有错误。而且您正在泄漏日志句柄。试试这个:

DWORD GetLogRecords(LPCWSTR wsLogFile)
{
  HANDLE hEvt = OpenEventLog(NULL, wsLogFile);
  if (hEvt==NULL) return 0;

  DWORD dwTotalRecords;
  BOOL res = GetNumberOfEventLogRecords(hEvt, &dwTotalRecords);
  CloseEventLog(hEvt);

  return (res != 0) ? dwTotalRecords : 0;
}

为了其他人的利益,这个问题的解决方案是 OpenEventLog 不接受路径名。相反,您必须为其提供事件日志的 源名称 (类似于 "HardwareEvents")。

如果您调用 OpenEventLog 时使用了无效的源名称(包括提供路径名),则如文档所述,它将改为打开 Application 日志:

If you specify a custom log and it cannot be found, the event logging service opens the Application log.