如何删除和创建登录 Windows 事件查看器

How to remove and create log in Windows Event Viewer

我有一个应用程序。我正在尝试在 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.

Exception Info: System.Exception at ServerApp.MainWindow..ctor()

Exception Info: System.Windows.Markup.XamlParseException at System.Windows.Markup.WpfXamlLoader.Load(System.Xaml.XamlReader, System.Xaml.IXamlObjectWriterFactory, Boolean, System.Object, System.Xaml.XamlObjectWriterSettings, System.Uri) at System.Windows.Markup.WpfXamlLoader.LoadBaml(System.Xaml.XamlReader, Boolean, System.Object, System.Xaml.Permissions.XamlAccessLevel, System.Uri) at System.Windows.Markup.XamlReader.LoadBaml(System.IO.Stream, System.Windows.Markup.ParserContext, System.Object, Boolean) at System.Windows.Application.LoadBamlStreamWithSyncInfo(System.IO.Stream, System.Windows.Markup.ParserContext) at System.Windows.Application.LoadComponent(System.Uri, Boolean) at System.Windows.Application.DoStartup()

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

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

该应用将使用哪个帐户运行 的用户需要具有访问权限才能创建日志。

祝你好运。

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

how to save exception in txt file?

您不必总是写入文件,而只是为了了解真正发生的事情