How to remove and create log in Windows Event View

2019-07-04 02:55发布

问题:

I have an app. I'm trying to write log in Windows Event Viewer when its crashing. I found Write to Windows Application Event Log and I'm using DispatcherUnhandledExceptionEventHandler for catching unhandled exception. I'm setting it in constructor of app like:

 DispatcherUnhandledException += MyApplication_DispatcherUnhandledException;

and write log like this:

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

Log creates, but in Run method of System.Windows.Application occurs another exception and windows adds this error in Event Viewer with another Id, source....

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()

How can I write only my log in 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);
    }
}

The user, under which account this app is going to run, needs to have access to be able to create logs.

Good luck.



回答2:

I would put a try catch around the whole process and then write the exception to a file see:

how to save exception in txt file?

You don't have to always write to the file but just to understand what is really going on