NLog configured to automatically log all exceptions?

女生的网名这么多〃 提交于 2020-01-12 03:10:08

问题


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

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


回答1:


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

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).

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).

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...).

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




回答2:


For WebApi application you can do this in Global.asax.cs like that

protected void Application_Error()
{
    Exception lastException = Server.GetLastError();
    NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
    logger.Fatal(lastException);
}

MSDN resource



来源:https://stackoverflow.com/questions/13895929/nlog-configured-to-automatically-log-all-exceptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!