"The description for Event ID" 使用 EntryWrittenEventHandler 访问事件消息时

"The description for Event ID" when using EntryWrittenEventHandler to access Event Message

我们正在使用以下 .NET 4.5 代码来捕获创建的事件日志条目:

var log = new EventLog("Application");
log.EnableRaisingEvents = true;
log.EntryWritten += new EntryWrittenEventHandler(OnEntryWritten);

// Define other methods and classes here
protected static void OnEntryWritten(object source, EntryWrittenEventArgs evt)
{
    var e = evt.Entry;
    var v = new
    {
        EntryType = e.EntryType,
        Index = e.Index,
        InstanceId = e.InstanceId,
        MachineName = e.MachineName,
        Message = e.Message,
        Source = e.Source,
        TimeGenerated = e.TimeGenerated.ToUniversalTime(),
        TimeWritten = e.TimeWritten.ToUniversalTime(),
        UserName = e.UserName,
    };
    v.Dump(); //Testing in LinqPad
}

但是条目显示的消息如下:

The description for Event ID '1903' in Source 'HHCTRL' cannot be found. The local computer may not have the necessary registry information or message DLL files to display the message, or you may not have permission to access them. The following information is part of the event:'http://go.microsoft.com/fwlink?LinkID=45839'

The description for Event ID '1' in Source 'scollector' cannot be found. The local computer may not have the necessary registry information or message DLL files to display the message, or you may not have permission to access them. The following information is part of the event:'service_windows.go:194: scollector service stopped'

这些消息在事件查看器中正确显示(描述没有错误),当我在 Powershell 中使用 get-winevent -LogName Application -MaxEvents 10 查看它们时它们也正确显示。

我尝试添加以下内容 PermissionSet 以确保我可以访问事件日志,但它仍然不起作用。

PermissionSet ps = new PermissionSet(PermissionState.Unrestricted);
ps.AddPermission(new RegistryPermission(RegistryPermissionAccess.AllAccess, System.Environment.MachineName));
ps.AddPermission(new EventLogPermission(EventLogPermissionAccess.Administer, System.Environment.MachineName));
ps.Demand();

该服务(或我们测试时的 LinqPad)是 运行 管理员,我已确认 HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\scollector\EventMessageFile 注册表项存在(我们的自定义服务仅使用 %SystemRoot%\System32\EventCreate.exe,因此所有消息格式都只是 %1 )。我们需要做什么来防止条目中包含 "The description for Event ID" 错误消息?

在这种情况下,似乎无法正常工作的应用程序使用了 REG_SZ 注册表类型作为 EventMessageFile 而不是 REG_SZ_EXPAND 注册表类型(将 %SystemRoot% 扩展为 c :\Windows 在返回值之前)。

REG_SZ_EXPAND is the required type, but in our case these were registered using just REG_SZ due to a bug in the winsvc/eventlog go package

一旦我删除并重新创建了具有正确类型的 EventMessageFile 密钥,它便开始按预期工作。