在客户端上记录WCF错误

时间:2012-07-09 13:44:53

标签: wcf wcf-client wcf-faults

我的应用程序使用WCF调用Web服务。呼叫可能由于各种原因而失败:

  • 故障
  • 超时
  • 连接丢失
  • ...

我想记录所有这些错误。我不想在try-catch中包装每个调用,而是希望在一个地方为整个应用程序中的所有Web服务调用执行此操作。

不幸的是,IClientMessageInspector不会因超时和连接失败而被调用。 是否有可用于集中记录所有异常的WCF扩展点?

请注意,我不只是想像WCF Tracing这样的文本记录错误。我想记录:

  • 的ServiceName
  • 方法名
  • 持续时间
  • Exception.ToString()

我愿意接受解决方法。

1 个答案:

答案 0 :(得分:1)

我不知道可扩展性点,但我可以提供我们使用过的解决方法。基本上,我们创建了一个“代理”,通过所有服务调用。下面是代理及其使用示例。

/// <summary>
/// Proxy for executing generic service methods
/// </summary>
public class ServiceProxy
{
    /// <summary>
    /// Execute service method and get return value
    /// </summary>
    /// <typeparam name="C">Type of service</typeparam>
    /// <typeparam name="T">Type of return value</typeparam>
    /// <param name="action">Delegate for implementing the service method</param>
    /// <returns>Object of type T</returns>
    public static T Execute<C, T>(Func<C, T> action) where C : class, ICommunicationObject, new()
    {
        C svc = null;

        T result = default(T);

        try
        {
            svc = new C();

            result = action.Invoke(svc);

            svc.Close();
        }
        catch (FaultException ex)
        {
            // Logging goes here
            // Service Name: svc.GetType().Name
            // Method Name: action.Method.Name
            // Duration: You could note the time before/after the service call and calculate the difference
            // Exception: ex.Reason.ToString()

            if (svc != null)
            {
                svc.Abort();
            }

            throw;
        }
        catch (Exception ex)
        {
            // Logging goes here

            if (svc != null)
            {
                svc.Abort();
            }

            throw;
        }

        return result;
    }
}

使用它的一个例子:

var result = ServiceProxy.Execute<MyServiceClient, MyReturnType>
(
    svc => svc.GetSomething(someId)
);