Windows事件日志 - 如何注册事件源?

16
我正在创建一个新的事件源,并使用下面的代码记录一条消息:
    static void Main(string[] args)
    {
        if (!EventLog.SourceExists("My Log"))
        {
            EventLog.CreateEventSource("My Application", "My Log");
            Console.WriteLine("Created new log \"My Log\"");
        }

        EventLog myLog = new EventLog("My Log");
        myLog.Source = "My Application";
        myLog.WriteEntry("Could not connect", EventLogEntryType.Error, 1001, 1);
    }

创建了一个名为“我的日志”的自定义事件日志(如预期所示),但消息被记录在“应用程序”节点下方。我做错了什么?
2个回答

23

MSDN中有如下说明:

如果某个源已经被映射到一个日志,并且您将其重新映射到一个新的日志,那么您必须重新启动计算机才能使更改生效。

在尝试编写到应用程序日志的代码时,如果您现在需要重启计算机才能“取消映射”该链接,那是否可能呢?


1
重启电脑后,该应用程序按预期运行。 - Captain Sensible
即使我通过编程删除源代码、日志和其他文件,我仍然需要重新启动 :) - PJUK
1
我希望我能点赞10次...我浪费了几个小时来弄清楚为什么每次我安装这该死的东西时它都会将我的源代码写入应用程序日志! - alexD

10

我认为你似乎有些混淆了。

你有一个源(即你的应用程序),而这个源与日志相关联,这是在创建源时完成的。 在你的代码开头你有些混淆了,实际上应该是:

    if (!EventLog.SourceExists("My Application"))

我刚刚写了一些代码来帮助我解决这个问题。在我遇到的另一个日志问题中,我不想手动从日志中删除源。 我的决定是检查源是否存在,如果存在,则检查它是否链接到正确的日志。如果没有链接到正确的日志,则删除该源。现在,既然它不存在或者从未存在过,则全新创建日志。

protected const string EventLogName = "MyLog";

private static bool CheckSourceExists(string source) {
  if (EventLog.SourceExists(source)) {
    EventLog evLog = new EventLog {Source = source};
    if (evLog.Log != EventLogName) {
      EventLog.DeleteEventSource(source);
    }
  }

  if (!EventLog.SourceExists(source)) {
    EventLog.CreateEventSource(source, EventLogName);
    EventLog.WriteEntry(source, String.Format("Event Log Created '{0}'/'{1}'", EventLogName, source), EventLogEntryType.Information);
  }

  return EventLog.SourceExists(source);
}

public static void WriteEventToMyLog(string source, string text, EventLogEntryType type) {      
  if (CheckSourceExists(source)) {          
      EventLog.WriteEntry(source, text, type);          
  }
}

希望它能帮到你 :)


我尝试将这个放在我的Service.cs构造函数中,但启动时出现了1053错误导致崩溃。 - obl
你需要在注册表中拥有事件日志文件夹的写入访问权限,否则,它仍然可以工作,但是1053对我来说没有任何意义,抱歉。 - PJUK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接