有没有一种方法可以配置NLog自动记录应用程序可能发送的所有异常?目前,我正在进入所有TRY/CATCH块并在CATCH中手动添加日志记录 - 但如果我错过了一些呢?如果将来有其他人做了同样的事情怎么办?
有没有一种方法告诉NLog始终记录所有异常?特别是一些未被捕获且可能导致弹出窗口的异常?
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_CurrentDomain_UnhandledException);
static void AppDomain_CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// use logger here to log the events exception object
// before the application quits
}
请注意,这只能让您记录导致应用程序崩溃的异常-您无法防止其崩溃(因此名称为未处理的异常)。Global.asax.cs
中这样做。protected void Application_Error()
{
Exception lastException = Server.GetLastError();
NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
logger.Fatal(lastException);
}
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_CurrentDomain_UnhandledException);
Object o = SomeMethodToThrowError(); // Cause an exception
}
static void AppDomain_CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// use logger here to log the events exception object
// before the application quits
Exception ex = (Exception)e.ExceptionObject;
Logger.Error(ex.Message + " " + ex.StackTrace);
}