EventLog.CreateEventSource未创建自定义日志

Jez*_*Jez 24 .net c# logging

我有一些像这样的代码:

EventLog.CreateEventSource("myApp", "myAppLog");
EventLog.WriteEntry("myApp", "Test log message", EventLogEntryType.Error);
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*aas 39

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

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

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

  • 耶稣基督谢谢你。近 2 个小时一直在敲我的头。 (3认同)

PJU*_*JUK 5

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

希望它有帮助:)