有没有办法将 NLog 配置为自动记录我的应用程序可以发送的所有异常?目前,我将访问所有 TRY/CATCH 块并在 CATCH 中手动添加日志记录 - 但如果我错过了一些怎么办?如果将来有人这样做怎么办
有没有办法告诉 NLog 总是记录所有异常?尤其是一些没有被捕获并可能导致弹出窗口的?
据我所知,没有办法限制 NLog 记录所有异常。
如果您只想记录未处理的异常,则可以在初始化应用程序时将“UnhandledException Handler”添加到 AppDomain。请注意,在某些情况下,可能无法记录错误(例如,在 OutOfMemory 异常或某些可怕的情况下)。
请注意,AppDomain 还具有您可以订阅的FirstChanceException 事件,但这意味着您会收到有关发生的每个异常的通知(并且可能由用户代码处理) - 这有很多。
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
}
请注意,这只允许您记录导致应用程序崩溃的异常 - 您无法阻止它崩溃(因此名称:未处理的异常)。
另一种选择是使用面向方面的编程(AOP) - 并在每次方法调用后引入一个日志方面,以防出现错误。如果您的应用程序使用分层架构,这可能相对容易做到(例如,为您的业务逻辑层的所有调用添加一个方面......)。
您可能会发现PostSharp或Spring.Net这样的框架很有用(通常他们的网站为此提供了一些简单的示例)。
对于WebApi应用程序,您可以这样Global.asax.cs
做
protected void Application_Error()
{
Exception lastException = Server.GetLastError();
NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
logger.Fatal(lastException);
}
Jacek 的回答对 WebApi 有好处。这是控制台应用程序的答案:
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);
}