C# 当引发未捕获的异常时,是否可以让.NET自动将异常消息写入事件日志?
我有一个非交互式应用程序,在实例化日志文件之前,我需要加载一些字符串字段。有一种方法可以将文本文件的内容读取到字段中。如果路径不存在,我希望应用程序事件日志中的异常列出尝试访问的路径。以下是我尝试过的:C# 当引发未捕获的异常时,是否可以让.NET自动将异常消息写入事件日志?,c#,.net,exception,C#,.net,Exception,我有一个非交互式应用程序,在实例化日志文件之前,我需要加载一些字符串字段。有一种方法可以将文本文件的内容读取到字段中。如果路径不存在,我希望应用程序事件日志中的异常列出尝试访问的路径。以下是我尝试过的: try { string contents = File.ReadAllText(path); } catch (FileNotFoundException) { throw new FileNotFoundException(string.Format("Path not f
try
{
string contents = File.ReadAllText(path);
}
catch (FileNotFoundException)
{
throw new FileNotFoundException(string.Format("Path not found: {0}",path));
}
使用此代码运行测试应用程序时,控制台窗口中的异常文本与预期的一样:
Unhandled Exception: System.IO.FileNotFoundException: Path not found: C:\temp\notthere.txt
但是,事件日志中记录的异常详细信息不包括异常消息文本:
Application: ConsoleApp3.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
at ConsoleApp3.Program.Main(System.String[])
是否可以让.NET自动记录更多异常详细信息,或者我只需要添加代码自己写入事件日志?您可以采取的一种方法是处理事件: 通过处理此事件,您有机会对异常做出反应,您可以自己将异常写入事件日志或自己的日志记录目标
请务必注意,当您使用此异常处理程序时,您确实应该将应用程序基础结构的其余部分视为可能已损坏,并避免在捕获所需数据之外执行过多操作。捕获
FileNotFoundException
异常并抛出新的异常,因此失去了可能有用的细节。至少将以前的异常作为内部异常附加。谢谢,但我想知道是否有办法让.NET将异常消息包含在它本机创建的事件日志条目中。看起来答案是“不”,但我很感谢您的输入。@MikeBruno,我恐怕不知道这一点:(我唯一的猜测是,事件日志条目的大小有一个最大限制,并且具有“核心”。net基础设施包含的内容可能会超过此限制,这就是为什么它不是一个选项的原因:)
using System;
using System.Diagnostics;
namespace Scratch
{
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
throw new Exception("Uh oh!");
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
using (var eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry($"Unhandled exception {(e.ExceptionObject as Exception).Message}");
}
}
}
}