views:

1423

answers:

6

I'm trying to implement an IErrorHandler in my WCF service in order to log every exception that hits the service boundary before it's passed to the client. I already use IErrorHandlers for translating Exceptions to typed FaultExceptions, which has been very useful. According to the MSDN for IErrorHandler.HandleError(), it's also intended to be used for logging at the boundary.

The problem is, the HandleError function isn't guaranteed to be called on the operation thread, so I can't figure out how to get information about what operation triggered the exception. I can get the TargetSite out of the exception itself, but that gives me the interior method instead of the operation. I could also parse through the StackTrace string to figure out where it was thrown, but this seems a little fragile and hokey. Is there any consistent, supported way to get any state information (messages, operationdescription, anything) while in the HandleError function? Or any other ways to automatically log exceptions for service calls?

I'm looking for a solution to implement on production, using my existing logging framework, so SvcTraceViewer won't do it for me.

Thanks.

+1  A: 

I use the IErrorHanlder in the same way that you describe, but not for logging. Instead on service classes (WCF or not) I use an interceptor as described here. I believe that this technique will capture the information you are interested in.

Tim Scott
AOP always freaks me out but looks very applicable here. Thank you for sharing.
smaclell
A: 

Have you used the Service Trace Viewer?

Mark Cidade
+1  A: 

I ended up putting the logging in IErrorHandler.ProvideFault() instead of IErrorHandler.HandlerError(). The ProvideFault call is made in the operation thread, so I can use OperationContext.Current to get some information to log.

Eric W
A: 

The ProvideFault() operations is being called on the incoming call thread and the client is still blocked waiting for response. I don't think it is good idea to add a lengthy process(like logging) inside this method. That is why they exposed another operation HandleError whch gets called on a separate worker thread.

But I understand your situation. Please share if you found a solution other than logging inside ProvideFault.

A: 

What about creating an instance and saving the request message on that instance?

A: 

You could stash any context information you need to log in the Exception's Data dictionary in the ProvideFault method which is called on the operation thread...then reference it in the HandleError method for logging purposes.

WayneC