NLog配置为自动记录所有异常? [英] NLog configured to automatically log all exceptions?

查看:502
本文介绍了NLog配置为自动记录所有异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将NLog配置为自动记录我的应用程序可以发送的所有异常?目前,我将转到所有TRY/CATCH块,并在CATCH中手动添加日志记录-但是如果我错过了一些记录该怎么办?还有,如果将来有人这样做

Is there a way to configure NLog to automatically log all exceptions my application can send? Currently I am going to all TRY/CATCH blocks and manually adding logging in the CATCH - but what if I miss some? And what if in the future someone else does

是否有一种方法可以告诉NLog仅记录所有异常?尤其是某些未被捕获并可能导致弹出窗口的信息?

Is there a way to tell NLog to just always log all exceptions? Esspecially some that are not caught and could cause a popup?

推荐答案

据我所知,没有办法用confineNLog记录所有异常.

As far as I know, there is no way to confineNLog to log all exceptions.

如果只想记录未处理的异常,则可以在初始化应用程序时向AppDomain添加"UnhandledException Handler". 请注意,在某些情况下,可能无法记录该错误(例如,在发生OutOfMemory异常或可怕的情况下).

If all you want is to log unhandled exceptions, you could add an "UnhandledException Handler" to the AppDomain when initializing your application. Note that under some circumstances it may not be possible to log the error (e.g. in case of an OutOfMemory exception or something terrible).

请注意,AppDomain还具有您可以订阅的 FirstChanceException事件,但这意味着您会收到有关发生的每个异常的通知(并且可能由用户代码处理)-在这种情况下很多.

Note that the AppDomain also has a FirstChanceException event you can subscribe to, but this would mean that you get notified about every exception that occurs (and may be handled by the usercode) - in this are many.

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
}

请注意,这仅允许您记录导致应用程序崩溃的异常-您无法阻止其崩溃(因此,名称为:未处理的异常).

Note that this will only allow you to log exceptions that cause your application to crash - you cannot prevent it to crash (therefore the name: unhandled exception).

另一种选择是使用面向方面的编程(AOP)-并在每次方法调用后引入Logging方面,以防出现错误.如果您的应用程序使用分层体系结构,则这可能相对容易做到(例如,向您的业务逻辑层的所有调用添加方面 ...).

Another option would be to use Aspect Oriented Programming (AOP) - and introduce a Logging aspect after each method call, in case of an error. If your application uses a Layered architecture, this may be relatively easy to do (e.g. add an aspect to all calls of your business logic layer...).

您可能会找到类似 PostSharp

You may find a framework like PostSharp or Spring.Net useful (usually their websites provide some easy examples for that).

这篇关于NLog配置为自动记录所有异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆