在不同的事件日志中创建以前删除的源不起作用

Ste*_*yer 3 c# powershell eventlog-source

在测试 log4net EventLogAppender 期间,我已经与 Windows 事件日志进行了长时间的斗争,其行为不一致,我意识到 log4net 代码有效,但我的 Windows 事件日志是不合理的。

系统

  • 操作系统:Windows 8.1
  • C#:.Net 4.5,针对 x64 构建

创建错误案例

  • C#:在 TestLog1 中创建 Source1
  • C#:写入日志(有效)
  • Powershell:使用 powershell 删除日志
  • C# 在 TestLog2 中创建 Source1(不同日志)
  • C# 写入日志 <= 这表明 TestLog2 中没有日志条目!

我已经制作了完整的分步指南来重现问题:

1:在新日志中创建新源并写入

执行代码:

EventLog.CreateEventSource(source: "TestSource1", logName: "TestLog1");
EventLog myLog = new EventLog();
myLog.Source = "TestSource1";
myLog.WriteEntry("This is a message");
Run Code Online (Sandbox Code Playgroud)

使用 powershell 命令列出日志:

Get-EventLog -LogName *
Run Code Online (Sandbox Code Playgroud)

这将正确列出所有日志,包括包含 1 个日志条目的 TestLog1。我还可以使用以下 powershell 命令获取日志条目:

GetEventLog -LogName "TestLog1"
Run Code Online (Sandbox Code Playgroud)

这显示了日志中的单个日志消息。

2:使用powershell删除事件日志

Powershell命令:

Remove-EventLog -LogName "TestLog1"
Run Code Online (Sandbox Code Playgroud)

现在列出所有日志显示该日志实际上已被删除。再次使用 Powershell 命令:

Get-EventLog -LogName *
Run Code Online (Sandbox Code Playgroud)

3:再次创建源,但这次在另一个日志中

执行代码:

EventLog.CreateEventSource(source: "TestSource1", logName: "TestLog2"); // New log name
EventLog myLog = new EventLog();
myLog.Source = "TestSource1";
myLog.WriteEntry("This is a message");
Run Code Online (Sandbox Code Playgroud)

结果:

  • 列出所有日志时,该日志会出现在 powershell 中
  • 日志不包含任何条目
  • 使用 Get-EventLog“TestLog2” 会引发异常,即使它出现在日志列表中
  • 使用remove-eventlog -logName“TestLog2”删除powershell中的日志不知何故仍然有效。

似乎在某些情况下,日志似乎存在,但在其他情况下则不存在。

答:这是一个已知的错误还是我的场景有什么问题?

B:如果源以某种方式仍然存在指向旧日志,我该如何清理现有的混乱?(如果是这样的话,那就是)

编辑:我什至尝试使用以下 C# 代码先删除源,然后删除日志,但结果是相同的:

var source = "TestSource6";
var logName1 = "Testlog5";
var logName2 = "Testlog6";

EventLog.CreateEventSource(source: source, logName: logName1);

new EventLog() { Source = source }.WriteEntry("This is a message in log " + logName1);

EventLog.DeleteEventSource(source:source);
EventLog.Delete(logName:logName1);

EventLog.CreateEventSource(source: source, logName: logName2);
new EventLog() { Source = source }.WriteEntry("This is a message" + logName2);
Run Code Online (Sandbox Code Playgroud)

Oct*_*oid 5

不幸的是,您无法“连续”重新注册事件源。这是安装人员经常要求重新启动计算机的(众多)原因之一。

来自 MSDN:

如果源已映射到日志并且您将其重新映射到新日志,则必须重新启动计算机才能使更改生效。

EventLog.CreateEventSource 方法(字符串、字符串)

为了解决该问题,我建议不要删除事件源,除非卸载产品。只需停止使用 Log1 并开始使用 Log2,无需删除和重新创建。当您要使用任何日志时,您可以使用类似于以下内容的内容:

if (!EventLog.SourceExists(source, log))
{
    EventLog.CreateSource(source, log)
}
Run Code Online (Sandbox Code Playgroud)

只需将源保留在原来的位置,直到卸载该产品。如果您使用InstallShield,它应该自动检测是否需要重新启动并要求用户这样做。