如何在Windows事件查看器中删除和创建日志

4

我有一个应用程序。当它崩溃时,我想要将日志写入 Windows事件查看器。我找到了写入Windows应用程序事件日志,并使用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, Boolean, System.Object, System.Xaml.XamlObjectWriterSettings, System.Uri) 中发生 在 System.Windows.Markup.WpfXamlLoader.LoadBaml(System.Xaml.XamlReader, Boolean, System.Object, System.Xaml.Permissions.XamlAccessLevel, System.Uri) 中发生 在 System.Windows.Markup.XamlReader.LoadBaml(System.IO.Stream, System.Windows.Markup.ParserContext, System.Object, Boolean) 中发生 在 System.Windows.Application.LoadBamlStreamWithSyncInfo(System.IO.Stream, System.Windows.Markup.ParserContext) 中发生 在 System.Windows.Application.LoadComponent(System.Uri, Boolean) 中发生 在 System.Windows.Application.DoStartup() 中发生

如何在事件查看器中只记录我的日志?


看起来你的事件处理程序没有处理那个异常。这个异常是不是在未处理异常的处理程序被添加之前抛出的? - Cee McSharpface
你是否像 CodeCoaster 的回答一样创建了一个新的事件日志? - jdweng
尝试将那个using代码块注释掉。在我看来,你有一个未处理的异常。 - spodger
2个回答

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

用户需要拥有访问权限才能创建日志,这是使用此应用程序的账户。

祝好运。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接