WinAPI ReportEvent - 未安装组件

WinAPI ReportEvent - component not installed

我已经实现了一个简单的功能来从我的应用程序登录事件查看器。但是,无论错误级别如何,每次我记录内容时都会收到以下消息:

The description for Event ID 0 from source MyAppEvents cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.

If the event originated on another computer, the display information had to be saved with the event.

我不是事件日志方面的专家,实际上,这是我第一次在 C++ 中使用它,文档令人困惑和误导...

这是我实现的封装事件日志调用的方法:

HANDLE source = NULL;

void app_log(std::string m, WORD level) {
    std::wstring msg_temp (m.begin(), m.end());
    LPCWSTR msg = msg_temp.c_str();

    std::wstring name(L"MyAppEvents");
    if (source == NULL) 
        source = RegisterEventSource(NULL, name.c_str());
    if (source) {
        if (!ReportEvent(source, level, 0, 0, NULL, 1, 0, &msg, NULL))
            std::cerr << "Error when logging";
    }
    else 
        std::cerr << "Error when logging";
}

我的应用程序有一个安装程序,它是用 WIX 构建的(此安装程序创建了登录事件查看器所需的密钥 - 应用程序的子密钥)并且运行顺利。但是,我不理解该消息,也不知道如何将我安装的应用程序附加到事件日志 - 实际上我什至不确定这是否是问题所在,或者它是否可能是我的参数之一'传递为 NULL0

当我调试时也会出现此消息(没有安装,但手动创建了“应用程序子项”)。

你能帮帮我吗?

我不能使用 C++ 托管代码...

您的日志记录代码没有任何问题。警告消息仅表示您没有在注册表中正确注册 MyAppEvents 事件源。这记录在 MSDN 上:

RegisterEventSource function:

pSourceName [in]
The name of the event source whose handle is to be retrieved. The source name must be a subkey of a log under the Eventlog registry key. Note that the Security log is for system use only.

Event Sources:

The structure of the event sources is as follows:

HKEY_LOCAL_MACHINE
   SYSTEM
      CurrentControlSet
         Services
            EventLog
               Application
                  AppName
               Security
               System
                  DriverName
               CustomLog
                  AppName

...

Each event source contains information (such as a message file) specific to the software that will be logging the events

...

An application can use the Application log without adding a new event source to the registry. If the application calls RegisterEventSource and passes a source name that cannot be found in the registry, the event-logging service uses the Application log by default. However, because there are no message files, the Event Viewer cannot map any event identifiers or event categories to a description string, and will display an error. For this reason, you should add a unique event source to the registry for your application and specify a message file.

仅仅创建 MyAppEvents 子键是不够的,您还必须将它指向您应用的消息文件。如果您将事件日志类别和事件消息存储为应用程序可执行文件的资源,则该子项可以将可执行文件本身注册为消息文件。