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

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

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

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

MSDN中有以下注释:

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

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

你觉得在某些地方看起来有些混乱。

你有一个源(这是你的应用程序),并且该源链接到一个Log,这是在你创建你的源码时完成的你在代码的开头有一点混合,它实际上应该是

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

我刚刚写了一些代码来帮助我解决这个问题。 在我遇到的另一个日志问题中注册的源,并且不希望手动从日志中删除源。 我决定做的是检查源是否存在,是否检查它是否链接到正确的日志,如果它不是删除源,现在它不存在或者它从未创建过Log new new 。

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

希望它有帮助:)