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

问题描述 投票:0回答:2

我正在创建一个新的事件源并使用以下代码记录消息:

    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);
    }

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

c# .net event-log
2个回答
22
投票

MSDN中有如下注释:

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

是否有可能在尝试之前尝试写入应用程序日志的代码时,现在需要重新启动才能“取消映射”该链接?


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);          
  }
}

希望有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.