代码之家  ›  专栏  ›  技术社区  ›  Captain Sensible

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

  •  14
  • Captain Sensible  · 技术社区  · 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 回复  |  直到 11 年前
        1
  •  18
  •   jp2code    11 年前

    在msdn中有以下注释:

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

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

        2
  •  10
  •   PJUK    15 年前

    我想你好像在那里把事情搞混了。

    您有一个源(即您的应用程序),该源链接到一个日志,这是在您创建源时完成的。 在代码的开头,您已经将这些混合了一点,实际上应该是

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

    希望有帮助:)

    推荐文章