Jader Dias
Jader Dias

Reputation: 90475

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?

Upvotes: 5

Views: 698

Answers (9)

Dave Hanson
Dave Hanson

Reputation: 525

A previous poster brought up AOP (Aspecte-Oriented Programming).

I use PostSharp for basic logging traces/exceptions.

It's quite easy to use and setup.

Check out this link and watch the tutorial.

http://www.sharpcrafters.com/postsharp

--crap it is no longer open source ... anyways you can grab Postsharp1.5 and mess around with it to see if it is something you are interested in it.

I am also in no way affiliated with PostSharp. I'm just a user.

Upvotes: 0

smencer
smencer

Reputation: 1053

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.

Upvotes: 4

Daniel Coffman
Daniel Coffman

Reputation: 2005

If all you're doing in your catch is logging the exception, you could maybe just use a custom error page and let ELMAH log all your uncaught exceptions.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283634

Exception filters would be good for this. Alas, .NET supports them through MSIL, C++/CLI, VB.NET, but not C#.

Upvotes: 1

empi
empi

Reputation: 15881

In such cases I always use centralized error handlers. In WCF it is very easy. Some more details: http://www.haveyougotwoods.com/archive/2009/06/24/creating-a-global-error-handler-in-wcf.aspx

Basically, you just implement the IServiceBehavior interface and then provide your own error handler. That is the best way to do this because you don't have to write any code that handles fatal exceptions (I mean exceptions that you can only log and you don't know what to do about them) in your methods.

Upvotes: 3

noocyte
noocyte

Reputation: 2522

If all your doing is logging then just log the error at a later stage... No need to log the error early. If you do more than log the error, well then you're gonna need the try..catch anyway. And if you swallow exceptions (IE. just log them and then go on as if nothings happened) then maybe you're doing it wrong...

Upvotes: 2

Jader Dias
Jader Dias

Reputation: 90475

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.

Upvotes: 4

John Saunders
John Saunders

Reputation: 161773

I once used something like the Template Function Pattern to resolve a problem like this. I had a base class that did something like:

public void Execute()
{
    try
    {
        ExecuteImplementation();
    }
    catch (Exception ex)
    {
        // Log ex
    }
}

public abstract void ExecuteImplementation();

There was one derived class per web service operation. The derived classes each implemented ExecuteImplementation.

The web service operations did:

[WebMethod]
public Result WebOperation(Request request)
{
    WebOperationClass instance = new WebOperationClass(request);
    instance.Execute();
    return instance.Result;
}

Upvotes: 1

Anton Gogolev
Anton Gogolev

Reputation: 115741

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

Also, see this discussion here on SO.

Upvotes: 5

Related Questions