Basic Framework solution for Wcf communication (IV)-cross-cutting logs

Source: Internet
Author: User

The first article provides an overview of several types of logs:

All logs have a final base class. Let's take a look at this class:

[DataContract(Namespace = "WcfExtension")]    [KnownType(typeof(WcfExceptionInfo))]    [KnownType(typeof(ServerExceptionInfo))]    [KnownType(typeof(ClientExceptionInfo))]    [KnownType(typeof(WcfInvokeInfo))]    [KnownType(typeof(ServerInvokeInfo))]    [KnownType(typeof(ClientInvokeInfo))]    [KnownType(typeof(WcfMessageInfo))]    [KnownType(typeof(ServerMessageInfo))]    [KnownType(typeof(ClientMessageInfo))]    [KnownType(typeof(StartInfo))]    [KnownType(typeof(ServerStartInfo))]    [KnownType(typeof(ClientStartInfo))]    public abstract class AbstractLogInfo    {        [DataMember]        [PersistenceColumn(IsIndex = true)]        public string ID { get; set; }        [DataMember]        [PersistenceColumn(IsIndex = true)]        public string RequestIdentity { get; set; }        [DataMember]        [PersistenceColumn(IsIndex = true)]        public DateTime Time { get; set; }        [DataMember]        [PersistenceColumn(IsIndex = true)]        public string MachineName { get; set; }        [DataMember]        [PersistenceColumn(IsIndex = true)]        public string MachineIP { get; set; }        [DataMember]        public string ExtraInfo { get; set; }        public override string ToString()        {            StringBuilder sb = new StringBuilder();            this.GetType().GetProperties().ToList().ForEach(p =>            {                var o = p.GetValue(this, null);                sb.AppendLine(p.Name + ": " + o);                if (o is Dictionary<string, string>)                {                    var dic = o as Dictionary<string, string>;                    foreach (var key in dic)                    {                        sb.AppendLine(" " + key.Key + ": " + key.Value);                    }                }            });            return sb.ToString();        }    }

Important points:

1) here the logs will be saved in Mongodb, and some attributes will tell the log server whether the fields need to be indexed and whether database sharding is required.

2) each log will have a GUID as the ID, which is nothing special. Note that if an exception occurs in the method executed by the server, the exception ID is returned to the client in the Message. This exception ID is the ID of this exception log. The client can only receive messages about server exceptions, but not more stack information. There are two reasons: 1. reduce the size of the Fault message, 2. the client should not know so much about the server, and the client may not be able to understand the server exception. The server has its own exception log.

3) Each log will have a RequestIdentity, which is a request context Association field. Start when the client sends a request, go to the server for processing, and then go to the client to receive the feedback from the server. All call logs, exception logs, and message logs have the same RequestIdentity. In other words, you can use this RequestIdentity in the background to query other logs associated with one type of logs throughout the request process. For example, if the method execution fails when you view the client execution log, you can directly view the execution log of the corresponding Server failure, and the exception log corresponding to the server and the exception log corresponding to the client. If the message log is enabled, you can also find the messages sent and received by the corresponding client and the server.

4) each log contains the machine name and IP address and time. ExtraInfo stores some other information. Here, I am storing the method name for recording this log.

Each type of log has two types: server log and client log, which implement two interfaces respectively:

Internal interface IServerInfo

{

String ServiceName {get; set ;}

}

Internal interface IClientInfo

{

String ClientTypeName {get; set ;}

String ContractName {get; set ;}

}

In my opinion, server logs need to focus on the service type, while client logs focus on the contract type and the class that calls the contract (such as the type name of a page ), this allows you to easily locate problems. Because the service implementation location is relatively fixed, there are a variety of places to call the service interface.

Let's take a look at what other log types have added:

    [DataContract(Namespace = "WcfExtension")]    public abstract class WcfExceptionInfo : AbstractLogInfo    {        [DataMember]        [PersistenceColumn(IsIndex = true)]        public string Type { get; set; }        [DataMember]        public string Message { get; set; }        [DataMember]        public string StackTrace { get; set; }    }

The exception log records the exception type, exception message, and stack.

    [DataContract(Namespace = "WcfExtension")]    public abstract class WcfMessageInfo : AbstractLogInfo    {        [DataMember]        public MessageDirection MessageDirection { get; set; }        [DataMember]        public string Message { get; set; }    }}

The message log records the complete message and message direction.

    [DataContract(Namespace = "WcfExtension")]    [KnownType(typeof(ApplicationContext))]    public abstract class WcfInvokeInfo : AbstractLogInfo    {        [DataMember]        public long ExecutionTime { get; set; }        [DataMember]        public bool IsSuccessuful { get; set; }        [DataMember]        public string MethodName { get; set; }        [DataMember]        public ApplicationContext ApplicationContext { get; set; }    }

Call the message to record the method name, whether the execution method is successful, the execution time, and some context information.

The final startup log records the information of the service interface obtained by the server and the startup and client for the first time:

    [DataContract(Namespace = "WcfExtension")]    [KnownType(typeof(WcfService))]    public class ServerStartInfo : StartInfo , IServerInfo    {        [DataMember]        public string ServiceName { get; set; }        [DataMember]        public WcfService WcfService { get; set; }    }    [DataContract(Namespace = "WcfExtension")]    public class ClientStartInfo : StartInfo , IClientInfo    {        [DataMember]        public string ContractName { get; set; }        [DataMember]        public string ClientTypeName { get; set; }        [DataMember]        public WcfEndpoint WcfEndpoint { get; set; }    }

In the previous article, we saw that the client's execution logs and exception logs are implemented in ServiceRealProxy, And the startup logs are implemented in the CreateServiceClient method in WcfServiceClientFactory. So where is the message log implemented?

Internal class ClientMessageInspector: IClientMessageInspector {private static Dictionary <string, string> contractVersionCache = new Dictionary <string, string> (); private static object locker = new object (); public void AfterReceiveReply (ref Message reply, object correlationState) {# if DEBUG var message = reply. toString (); Console. writeLine ("message received by the Client:" + message); # endif ClientApplicationContext. cu Rrent = reply. getApplicationContext <ClientApplicationContext> (); try {if (WcfLogManager. current (correlationState as Type )). messageInfo. client. enabled) {var direct = WcfLogManager. current (correlationState as Type )). messageInfo. client. direction; if (direct = WcfDirection. both | direct = WcfDirection. receive) {var log = WcfLogProvider. getClientMessageInfo (correlationState as Type ). fullName, ClientApplicationContext. current. requestIdentity, "ClientMessageInspector. afterReceiveReply ", MessageDirection. receive, reply. toString (); WcfServiceLocator. getLogService (). logWithoutException (log) ;}} catch (Exception ex) {LocalLogService. log (ex. toString () ;}} public object BeforeSendRequest (ref Message request, IClientChannel channel) {try {var channelType = channel. getType (); var serve RContext = new ServerApplicationContext (); serverContext. RequestIdentity = Guid. NewGuid (). ToString (); serverContext. ClientMachineName = WcfLogProvider. MachineName; if (! ContractVersionCache. ContainsKey (channelType. FullName) {lock (locker) {if (! ContractVersionCache. containsKey (channelType. fullName) {contractVersionCache. add (channelType. fullName, channelType. assembly. getName (). version. toString () ;}} serverContext. clientVersion = contractVersionCache [channelType. fullName]; request. setApplicationContext (serverContext); var clientContext = new ClientApplicationContext (); clientContext. requestIdentity = serverContext. requestIdentity; ClientApplicationContext. current = clientContext; # if DEBUG var message = request. toString (); Console. writeLine ("the client sends a message:" + message); # endif if (WcfLogManager. current (channel. getType ()). messageInfo. client. enabled) {var direct = WcfLogManager. current (channel. getType ()). messageInfo. client. direction; if (direct = WcfDirection. both | direct = WcfDirection. send) {var log = WcfLogProvider. getClientMessageInfo (channelType. fullName, ClientApplicationContext. current. requestIdentity, "ClientMessageInspector. beforeSendRequest ", MessageDirection. send, request. toString (); WcfServiceLocator. getLogService (). logWithoutException (log) ;}} return channelType;} catch (Exception ex) {LocalLogService. log (ex. toString ();} return channel. getType ();}}

Obviously, using IClientMessageInspector, the extended Wcf can be summarized as follows:

1) implement some interfaces defined by Wcf

2) Add the implementation to the XX behavior through code

3) add XX behavior to the Wcf through code or configuration file

The second step is as follows:

internal class MessageInspectorEndpointBehavior : IEndpointBehavior    {        #region IEndpointBehavior Members        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)        {        }        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)        {            clientRuntime.MessageInspectors.Add(new ClientMessageInspector());        }        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)        {            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new ServerMessageInspector());        }        public void Validate(ServiceEndpoint endpoint)        {        }        #endregion    }

The implementation of step 3 has been seen before, and is directly added when the channel factory is created. Let's take a look at the implementation of ClientMessageInspector. There are several points to note:

1) You can use WcfLogManager to read whether or not to record various logs. Then, you can use WcfLogProvider to obtain various logs. Finally, you can use WcfServiceLocator. GetLogService () to obtain log records of Log service.

2) Here, the version number of the contract is cached for performance. It should be noted that because these cross-cutting logs run through the framework and run through each method call, we must ensure high performance and ensure no errors, service processing performance cannot be greatly reduced for some logs, or even affect normal service operation.

3) return the contract type through correlationState, because it is difficult to extract the contract type in AfterReceiveReply.

Let's talk about the server side. The server side's method call log is implemented through IOperationInvoker. The specific implementation is not provided.

The message log of the server is obviously implemented through the IDispatchMessageInspector corresponding to IClientMessageInspector.

Finally, the server exception is implemented through IErrorHandler:

Internal class ErrorHandler: IErrorHandler {public bool HandleError (Exception error) {try {# if DEBUG Console. WriteLine ("server Exception! Message: {0}, id: {1} ", error. message, error. data ["id"]); # endif if (WcfLogManager. current (). predictioninfo. server. enabled) {var exceptionID = error. data ["id"]. toString (); var log = WcfLogProvider. getServerExceptionInfo ("ErrorHandler. handleErrer ", error); log. ID = exceptionID; WcfServiceLocator. getLogService (). logWithoutException (log) ;}} catch (Exception ex) {LocalLogService. log (ex. toString ();} return true;} public void ProvideFault (Exception error, MessageVersion version, ref Message fault) {try {var errorid = Guid. newGuid (). toString (); error. data. add ("id", errorid); ServerApplicationContext. current. serverExceptionID = errorid; FaultException fe = new FaultException (new FaultReason (error. message); MessageFault messagefault = fe. createMessageFault (); fault = Message. createMessage (version, messagefault, "http://www.5173.com");} catch (Exception ex) {LocalLogService. log (ex. toString ());}}}

Note the following two points:

1) When ProvideFault is used, we will encapsulate the exception as a FaultException and provide it to the client.

2) The server exception ID is transmitted to the client in the message header. This exception ID is the exception ID recorded by the server.

We may also note that the client needs to pass the RequestIdentity to the server, and the server needs to send the exception ID to the client. The client needs to pass the contract version to the server and the machine name of the client, the server also needs to pass its machine name and contract version to the client. This is done by defining the context class and passing it in the message header:

1) In IClientMessageInspector, prepare the context required by the server before sending the message, add it to the header for transmission, and establish the context of the client after receiving the message returned by the server.

2) In IDispatchMessageInspector, and 1) in turn, establish the server context after receiving the message, and prepare the context data required by the client to be added to the header before sending a reply.

With these rich log information, we can:

1) know the service startup information and which clients use our server.

2) know the client call information, the server's execution method information, and whether the versions at both ends match. You can count the machines on the client and server, and know the method execution time.

3) The client can associate the server with an exception. The server exception records the detailed error stack.

4) if you need to further track the problem, you can enable the message record (consuming a certain amount of performance)

5) change the client and server calls to a whole through context

6) because the machine names or IP addresses are recorded, you can calculate the machines with performance problems and locate the machines with errors in case of any problems, so that you can locate the problems in the Server Load balancer environment.

For distributed services, the server may be the client of other services, which is complicated and the cross-cutting concerns are particularly important, because a large part of this framework is implementing this.

Of course, it is not enough to store logs. You also need a powerful background for viewing and collecting logs to locate problems.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.