【发布时间】:2012-10-06 09:59:31
【问题描述】:
如何将未处理的异常记录到 WinForms 应用程序的日志文件中,以便轻松确定异常的来源?
【问题讨论】:
标签: vb.net winforms exception logging exception-handling
如何将未处理的异常记录到 WinForms 应用程序的日志文件中,以便轻松确定异常的来源?
【问题讨论】:
标签: vb.net winforms exception logging exception-handling
首先,您需要捕获未处理的异常。将此代码的 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# 代码!)
【讨论】:
在您的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
【讨论】:
如果您想记录某些内容,请使用 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。
【讨论】: