EventLog.CreateEventSource未创建自定义日志

我有一些像这样的代码:

EventLog.CreateEventSource("myApp", "myAppLog"); EventLog.WriteEntry("myApp", "Test log message", EventLogEntryType.Error); 

现在,除非我遗漏了读取MSDN的内容,否则会导致在事件查看器中创建新的日志“myAppLog”,并且应该将一个条目添加到源名为“myApp”的新日志中。 但是,我无法创建新日志。 这总是只是将错误日志消息写入应用程序日志,源“myApp” – “myAppLog”无处可见。 我究竟做错了什么? 我以管理员身份登录。

在写入标准应用程序日志时,您是否可能已使用源“myApp”? 如果是这样根据MSDN:

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

http://msdn.microsoft.com/en-us/library/2awhba7a.aspx (大约在页面的一半)

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

希望它有帮助:)

您可能忘记在EventLog上设置Source属性。

它应该看起来像这样:

  if(!EventLog.SourceExists("MySource")) { EventLog.CreateEventSource("MySource", "MyNewLog"); } EventLog myLog = new EventLog(); myLog.Source = "MySource"; myLog.WriteEntry("Writing to event log."); 

这是MSDN文章供参考。

你在EventLog上设置了源代码吗?

来自MSDN文章 。

必须先在EventLog组件实例上设置Source属性,然后才能将条目写入日志。 当组件写入条目时,系统会自动检查您指定的源是否已注册到组件正在写入的事件日志,并在需要时调用CreateEventSource。 通常,在安装应用程序期间创建新的事件源。 这允许操作系统刷新其已注册事件源列表及其配置的时间。 如果操作系统未刷新其事件源列表并且您尝试使用新源编写事件,则写入操作将失败。 如果在安装期间创建源不是一个选项,那么尝试在第一次写入操作之前创建源,可能在应用程序初始化期间。 如果选择此方法,请确保您的初始化代码在计算机上以管理员权限运行。 创建新事件源需要这些权限。

如果您已检查其他答案中的所有建议,请阅读以下内容

来自MSDN

操作系统将事件日志存储为文件。 使用EventLogInstaller或CreateEventSource创建新的事件日志时,关联的文件存储在指定计算机上的%SystemRoot%\ System32 \ Config目录中。 通过使用“.evt”文件扩展名附加Log属性的前8个字符来设置文件名。

确保前8个字符是唯一的。

基本上,最简单的解决方案是您必须关闭Visual Studio并以管理员模式运行。 然后,您将能够解决此错误