Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refactor logging in C#?

In my services all exposed methods have:

try
{
    // the method core is written here
}
catch(Exception ex)
{
    Log.Append(ex);
}

It's boring and ugly to repeat it over and over again. Is there any way to avoid that? Is there a better way to keep the service working even if exceptions occur and keep sending the exception details to the Log class?

like image 777
Jader Dias Avatar asked Mar 08 '10 20:03

Jader Dias


3 Answers

Try AOP. This is the most widely-used selling point of AOP.

Also, see this discussion here on SO.

like image 63
Anton Gogolev Avatar answered Sep 27 '22 23:09

Anton Gogolev


You could set up a generic error handling method for all uncaught exceptions like so:

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledException);

Depending on what went wrong, you may not be able to recover from the error... but this should hopefully give you some idea of what what went wrong. If it gets to the point where your application code hasn't handled the exception gracefully, this method could attempt to reinitialize the service to a known working state.

like image 22
smencer Avatar answered Sep 27 '22 23:09

smencer


I came up with a semi-solution right now. I can refactor the code:

public TResult ExecuteAndLogOnError(Func<TResult> func)
{
    try
    {
        return func();
    }
    catch(Exception ex)
    {
       // logging ...
    }
}

And then you can call it on each method:

return ExecuteAndLogOnError(() =>
{
    // method core goes here..
});

Which is 4 lines shorter than the original scenario.

like image 45
Jader Dias Avatar answered Sep 27 '22 23:09

Jader Dias