首页> C#>如何删除和创建Windows事件查看器中的日志
作者:互联网
我有一个应用.我正在尝试在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.Application的Run方法中发生另一个异常,并且Windows在Event Viewer中使用另一个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);
}
}
该应用程序将以哪个帐户运行的用户需要具有访问权限才能创建日志.
祝好运.
标签:event-log,event-viewer,c 来源: https://codeday.me/bug/20191108/2007476.html