背景:我正在维护一个集成平台,该平台从各种不可靠的API中提取数据。其中一些操作可能会产生高昂的成本,因此出于诊断目的,每个传出和传入的消息都会记录到磁盘中的一个单独文件中。对于类似REST的API,我在网络流上使用一个简单的包装器,它还将数据保存到文件中。对于.NETClassicSOAP客户端,我有一个助手可以动态包装SoapHttpClientProtocol
以使用相同的网络流日志记录机制。
对于.NET Standard 2.0和.NETCore,唯一受支持的编写SOAP客户端的方法是WCF。我如何以编程方式配置WCF SOAP客户端,以便将HTTP传入/传出流记录到单独的文件中,最好使用可配置的名称?
我当前的示例客户端代码:
public abstract class ServiceCommunicatorBase<T>
where T : IClientChannel
{
private const int Timeout = 20000;
private static readonly ChannelFactory<T> ChannelFactory = new ChannelFactory<T>(
new BasicHttpBinding(),
new EndpointAddress(new Uri("http://target/endpoint")));
protected T1 ExecuteWithTimeoutBudget<T1>(
Func<T, Task<T1>> serviceCall,
[CallerMemberName] string callerName = "")
{
// TODO: fixme, setup logging
Console.WriteLine(callerName);
using (var service = this.CreateService(Timeout))
{
// this uses 2 threads and is less than ideal, but legacy app can't handle async yet
return Task.Run(() => serviceCall(service)).GetAwaiter().GetResult();
}
}
private T CreateService(int timeout)
{
var clientChannel = ChannelFactory.CreateChannel();
clientChannel.OperationTimeout = TimeSpan.FromMilliseconds(timeout);
return clientChannel;
}
}
public class ConcreteCommunicator
: ServiceCommunicatorBase<IWCFRemoteInterface>
{
public Response SomeRemoteAction(Request request)
{
return this.ExecuteWithTimeoutBudget(
s => s.SomeRemoteAction(request));
}
}
我已经设法使用通过可配置行为附加的IClientMessageInspector
来记录消息。MSDN上有一些消息检查器的文档,但仍然很模糊(而且有些过时,netstandard-2.0
API表面略有不同。
我不得不从使用ChannelFactory<T>
转移到使用实际生成的代理类。工作代码(为简洁起见,剪切(:
var clientChannel = new GeneratedProxyClient(
new BasicHttpBinding { SendTimeout = TimeSpan.FromMilliseconds(timeout) },
new EndpointAddress(new Uri("http://actual-service-address"));
clientChannel.Endpoint.EndpointBehaviors.Add(new LoggingBehaviour());
服务类别:
// needed to bind the inspector to the client channel
// other methods are empty
internal class LoggingBehaviour : IEndpointBehavior
{
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new LoggingClientMessageInspector());
}
}
internal class LoggingClientMessageInspector : IClientMessageInspector
{
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var correlationId = Guid.NewGuid();
this.SaveLog(ref request, correlationId, "RQ");
return correlationId;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
var correlationId = (Guid)correlationState;
this.SaveLog(ref reply, correlationId, "RS");
}
private void SaveLog(ref Message request, Guid correlationId, string suffix)
{
var outputPath = GetSavePath(suffix, correlationId, someOtherData);
using (var buffer = request.CreateBufferedCopy(int.MaxValue))
{
var directoryName = Path.GetDirectoryName(outputPath);
if (directoryName != null)
{
Directory.CreateDirectory(directoryName);
}
using (var stream = File.OpenWrite(outputPath))
{
using (var message = buffer.CreateMessage())
{
using (var writer = XmlWriter.Create(stream))
{
message.WriteMessage(writer);
}
}
}
request = buffer.CreateMessage();
}
}
}