当前位置:首页 > 操作系统 > Windows

首页> C#>如何删除和创建Windows事件查看器中的日志

C#>如何删除和创建Windows事件查看器中的日志' />

我有一个应用.我正在尝试在Windows Event Viewer崩溃时编写日志.我发现Write to Windows Application Event Log,并且我正在使用DispatcherUnhandledExceptionEventHandler捕获未处理的异常.我在应用程序的构造函数中设置它,例如:

<code> DispatcherUnhandledException += MyApplication_DispatcherUnhandledException;
</code>

并这样写日志:

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

日志创建,但是在System.Windows.Application的Run方法中发生另一个异常,并且Windows在Event Viewer中使用另一个ID,源添加了此错误.

<code>Description: The process was terminated due to an unhandled exception.
</code>

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

如何只写我的登录事件查看器?

解决方法:

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

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

祝好运.


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐