Wednesday, October 26, 2016

How to Calculate Time Difference Between Request and Response in WSO2 ESB

If you want to calculate the time difference between request and response, we can use a script mediator.
The Script Mediator is used to script with languages such as JavaScript, Groovy, or Ruby.

First, you have to get request timestamp using a property mediator. For that, add below line inside "inSequence".
    
   <property name = "REQUEST_TIMESTAMP" expression = "get-property('SYSTEM_TIME')"/>  
   
Then, add below line inside "outSequence"  to get response timestamp.
    
   <property name = "RESPONSE_TIMESTAMP" expression = "get-property('SYSTEM_TIME')"/>  
   

Now, you can calculate response time using below code. (Script mediator)
    
   <script language = "js">  
      var requestTimeStamp = mc.getProperty("REQUEST_TIMESTAMP");  
      var responseTimeStamp = mc.getProperty("RESPONSE_TIMESTAMP");  
      var responseTime = responseTimeStamp - requestTimeStamp;  
      mc.setProperty( "RESPONSE_TIME", responseTime);  
   </script>  
   

A sample proxy with a script mediator to calculate response time is in below.
    
 <?xml version = "1.0" encoding = "UTF-8"?>   
  <proxy xmlns = "http://ws.apache.org/ns/synapse"   
    name = "CalculatingTimeDifference"   
   transports = "https,http"  
     statistics = "disable"  
     trace = "disable"  
     startOnLoad = "true">  
   <target>   
   <inSequence>   
      <property name = "REQUEST_TIMESTAMP" expression = "get-property('SYSTEM_TIME')"/>   
   </inSequence>   
   <outSequence> <sequence xmlns = "http://ws.apache.org/ns/synapse" name = "responseMessage">  
     <property name = "RESPONSE_TIMESTAMP" expression = "get-property('SYSTEM_TIME')"/>  
        <script language = "js">  
          var requestTimeStamp = mc.getProperty("REQUEST_TIMESTAMP");  
          var responseTimeStamp = mc.getProperty("RESPONSE_TIMESTAMP");  
          var responseTime = responseTimeStamp - requestTimeStamp;  
          mc.setProperty("RESPONSE_TIME", responseTime);  
      </script>  
      <log level = "custom">   
          <property name = "Response Time(ms)" expression = "$ctx:RESPONSE_TIME"/>  
          </log>  
    </outSequence>  
    </target>   
    <description/>   
  </proxy>   
   


You can see a log message like below with the response time.

[2016-10-03 09:41:43,531]  INFO - LogMediator API Response Time(ms) = 624.0

No comments:

Post a Comment