Microsoft Rest ServiceClientTracing - 如何将跟踪结果输出到Console或Debug?

时间:2017-10-25 23:42:40

标签: c# .net azure

ServiceClientTracing类具有static boolean IsEnabled属性,允许您打开跟踪。但是当你将属性设置为true时,Console / Debug或其他任何地方都没有显示输出。

如何设置跟踪以便在控制台/调试窗口(或任何地方)显示输出?

1 个答案:

答案 0 :(得分:6)

似乎默认情况下Microsoft.Rest.ClientRuntime项目不支持此功能,因此您需要为自己的类添加角色。例如:

class DebugTracer : IServiceClientTracingInterceptor
{
    public void Information(string message)
    {
        Debug.WriteLine(message);
    }

    public void TraceError(string invocationId, Exception exception)
    {
        Debug.WriteLine("Exception in {0}: {1}", invocationId, exception);
    }

    public void ReceiveResponse(string invocationId, HttpResponseMessage response)
    {
        string requestAsString = (response == null ? string.Empty : response.AsFormattedString());
        Debug.WriteLine("invocationId: {0}\r\nresponse: {1}", invocationId, requestAsString);
    }

    public void SendRequest(string invocationId, HttpRequestMessage request)
    {
        string requestAsString = (request == null ? string.Empty : request.AsFormattedString());
        Debug.WriteLine("invocationId: {0}\r\nrequest: {1}", invocationId, requestAsString);
    }

    public void Configuration(string source, string name, string value)
    {
        Debug.WriteLine("Configuration: source={0}, name={1}, value={2}", source, name, value);
    }

    public void EnterMethod(string invocationId, object instance, string method, IDictionary<string, object> parameters)
    {
        Debug.WriteLine("invocationId: {0}\r\ninstance: {1}\r\nmethod: {2}\r\nparameters: {3}",
            invocationId, instance, method, parameters.AsFormattedString());
    }

    public void ExitMethod(string invocationId, object returnValue)
    {
        string returnValueAsString = (returnValue == null ? string.Empty : returnValue.ToString());
        Debug.WriteLine("Exit with invocation id {0}, the return value is {1}",
            invocationId, returnValueAsString);
    }
}

Appropriated from Log4NetTracingInterceptor

现在,如果你想打开追踪,你需要做的就是:

ServiceClientTracing.IsEnabled = true;
ServiceClientTracing.AddTracingInterceptor(new DebugTracer());