【问题标题】:can I have .NET automatically write the exception message to the event log when an uncaught exception is thrown?当抛出未捕获的异常时,我可以让 .NET 自动将异常消息写入事件日志吗?
【发布时间】:2018-08-24 13:49:38
【问题描述】:

我有一个非交互式应用程序,我需要在实例化日志文件之前加载一些字符串字段。有一种方法可以将文本文件的内容读入字段。如果路径不存在,我希望应用程序事件日志中的异常列出试图访问的路径。这是我尝试过的:

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 异常并抛出新异常,从而丢失了可能有用的细节。至少将先前的异常附加为内部异常。

标签: c# .net exception


【解决方案1】:

您可以采取的一种方法是处理AppDomain.CurrentDomain.UnhandledException 事件:

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}");
            }
        }
    }
}

通过处理此事件,您有机会对异常做出反应,您可以自己将其写入事件日志,或写入您自己的日志记录目标。

请注意,当您在此异常处理程序中时,您确实应该将应用程序基础架构的其余部分视为可能已损坏,并且除了捕获您需要的数据之外避免做太多事情.

【讨论】:

  • 谢谢,但我想知道是否有办法让 .NET 在它本机创建的事件日志条目中包含异常消息。看起来答案是否定的,但我感谢您的意见。
  • @MikeBruno,我不知道,恐怕:(我唯一的猜测是事件日志条目的大小有一个最大限制,并且具有“核心”。网络基础设施包含的内容可能超过这就是它不是一个选项的原因:)
猜你喜欢
  • 1970-01-01
  • 2015-02-13
  • 2016-02-17
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
  • 2013-06-24
  • 2012-04-26
相关资源
最近更新 更多