【问题标题】:How to remove and create log in Windows Event Viewer如何在 Windows 事件查看器中删除和创建日志
【发布时间】:2019-05-11 11:13:39
【问题描述】:

我有一个应用程序。我正在尝试在Windows Event Viewer 崩溃时写入日志。我找到了Write to Windows Application Event Log,我正在使用DispatcherUnhandledExceptionEventHandler 来捕获未处理的异常。我将它设置在应用程序的构造函数中,例如:

 DispatcherUnhandledException += MyApplication_DispatcherUnhandledException;

并像这样写日志:

using (EventLog eventLog = new EventLog("Application"))
        {
            eventLog.Source = "Application";
            eventLog.WriteEntry(exceptionMessage, EventLogEntryType.Error);
        }

日志创建,但在System.Windows.ApplicationRun 方法中发生另一个异常,windows 在事件查看器中使用另一个 Id、源添加此错误....

Description: The process was terminated due to an unhandled exception.

异常信息:System.Exception 在 ServerApp.MainWindow..ctor()

异常信息:System.Windows.Markup.XamlParseException 在 System.Windows.Markup.WpfXamlLoader.Load(System.Xaml.XamlReader,System.Xaml.IXamlObjectWriterFactory,布尔,System.Object,System.Xaml.XamlObjectWriterSettings,System.Uri) 在 System.Windows.Markup.WpfXamlLoader.LoadBaml(System.Xaml.XamlReader,布尔,System.Object,System.Xaml.Permissions.XamlAccessLevel,System.Uri) 在 System.Windows.Markup.XamlReader.LoadBaml(System.IO.Stream,System.Windows.Markup.ParserContext,System.Object,布尔) 在 System.Windows.Application.LoadBamlStreamWithSyncInfo(System.IO.Stream,System.Windows.Markup.ParserContext) 在 System.Windows.Application.LoadComponent(System.Uri,布尔值) 在 System.Windows.Application.DoStartup()

我怎样才能只写我的登录事件查看器?

【问题讨论】:

  • 看起来您的事件处理程序没有处理该异常。会不会是在添加未处理异常的处理程序之前抛出了这个异常?
  • 您是否像 CodeCoaster 回答那样创建了新的事件日志?
  • 尝试注释掉 using 块。在我看来,您好像有一个未处理的异常。

标签: c# event-log event-viewer


【解决方案1】:
using System;
using System.Diagnostics;

...
...

public void WriteToEventLog(EventLogEntryType eventLogType, string message, string logSourceName)
{
    if (!EventLog.SourceExists(logSourceName))
    {
        EventLog.CreateEventSource(logSourceName, "Application");
    }
    using (var eventLog = new EventLog { Source = logSourceName })
    {
        const int maxLength = 31000;
        if (message.Length > maxLength)
        {
            message = message.Substring(0, maxLength);
        }
        eventLog.WriteEntry(message, eventLogType);
    }
}

此应用将在哪个帐户下运行的用户需要有权创建日志。

祝你好运。

【讨论】:

    【解决方案2】:

    我会在整个过程中尝试捕获,然后将异常写入文件 见:

    how to save exception in txt file?

    您不必总是写入文件,只需了解实际情况

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多