NLog - 绑定到UnhandledExceptionEventHandler时的记录困难

时间:2014-01-07 15:22:10

标签: c# nlog

我创建了一个控制台应用程序,可以在我直接从Main()登录时成功记录消息。我想要做的是设置一个处理程序来处理所有未处理的异常:

class Program
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            throw new ApplicationException("Throwing an unhandled exception!"); //This line keeps getting hit
            Console.ReadLine();
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var exc = (Exception)e.ExceptionObject;
            logger.ErrorException("Another exception occured!", exc);
        }
    }

这个应用程序永远不会卸载,我试图找出原因。它会抛出我的ApplicationException,然后执行CurrentDomain_UnhandledException(),然后调试器返回到行throw new ApplicationException()CurrentDomain_UnhandledException()再次被执行,然后我回到了将异常抛入无限及其后的行。

即使调用了logger.ErrorException(),也没有任何内容写入数据库。

1 个答案:

答案 0 :(得分:1)

对于第一部分,正常运行时调试之外会发生什么?

我怀疑是因为你在调试器调试时会调试解开callstack,因此你最终会回到抛出异常的同一个地方,所以继续抨击继续不会让你无处可去。

我相信可以选择阻止此行为,请参阅Tools >> Options >> Debugging >> General

但是我会保留它并接受它作为预期的行为(只要在调试之外正确处理未处理的异常)。

enter image description here

关于第二部分,我不确定它可能是你使用的任何一个appender根本没有机会冲洗。我切换到文件,看看它是否记录在那里检查。