How to remove and create log in Windows Event Viewer

老子叫甜甜 提交于 2019-12-10 19:16:40

问题


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



来源:https://stackoverflow.com/questions/53707610/how-to-remove-and-create-log-in-windows-event-viewer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!