【问题标题】:Logging unhandled exceptions to a log file将未处理的异常记录到日志文件
【发布时间】:2012-10-06 09:59:31
【问题描述】:

如何将未处理的异常记录到 WinForms 应用程序的日志文件中,以便轻松确定异常的来源?

【问题讨论】:

    标签: vb.net winforms exception logging exception-handling


    【解决方案1】:

    首先,您需要捕获未处理的异常。将此代码的 VB.Net 版本添加到您的主程序中:

    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    Application.ThreadException += ApplicationThreadException;
    AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
    

    然后添加事件处理程序:

    static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
    {
        Exception ex = e.ExceptionObject as Exception;
        if (ex != null)
        {
           Console.WriteLine("Unhandled exception: {0}", e.Exception);      
        }
    }
    
    static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
    {
        Console.WriteLine("Unhandled application exception: {0}", e.Exception);
    }
    

    然后您可以使用您选择的日志方法记录错误..(对不起 C# 代码!)

    【讨论】:

    • 如果我使用 try catch @ form 级别,那么我必须在 catch 块中写什么才能执行上面的代码?
    • 如果您使用 try/catch,只需将日志记录代码添加到 catch 块 - 这是为了获取 未处理 异常,即未在 try 中捕获的异常/catch 块。
    【解决方案2】:

    在您的Sub Main 或启动表单的构造函数中,添加以下代码:

    AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledExceptionHandler
    

    然后,将以下方法添加到您的Sub Main,或将其添加为任何其他类/表单中的共享方法:

    Public Sub UnhandledExceptionHandler(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
        If TypeOf e.ExceptionObject Is Exception Then
            Dim ex As Exception = CType(e.ExceptionObject, Exception)
            ' Log the exception
        End If
    End Sub
    

    【讨论】:

      【解决方案3】:

      如果您想记录某些内容,请使用 Nlog - 它会将日志消息写入文件、电子邮件等。 关联: http://nlog-project.org/

      文档: https://github.com/nlog/nlog/wiki/Tutorial

      那么你可以简单地这样做:

      Private Logger As NLog.Logger = NLog.LogManager.GetCurrentClassLogger
      try
      'do stuff
      catch
      logger.fatal("Messagedescription")
      end try
      

      这会自动将您的消息写入 nlog.config 文件中指定的文件 要查看日志,您可以使用我喜欢的任何编辑器或 logExpert。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-10
        • 1970-01-01
        • 2010-09-09
        • 1970-01-01
        • 2014-10-28
        • 2011-10-20
        • 2020-10-01
        • 2020-12-09
        相关资源
        最近更新 更多