Martkos IT Ltd

View Original

JMeter write full response messages to file

When you require a deeper level of log from Apache Jmeter you can use the Groovy programming language and a JSR223 sampler to extract the required values from variables within Jmeter and write them out to a file.

In the code below we trap all returned HTTP status codes in the range of HTTP 400 and above.

NOTE : Writing data to files can limit the throughput of your test. So where you intend to push through high workloads this level of logging may become obstructive.

import org.apache.jmeter.services.FileServer

//Create a new File instance by using the path defined
def inputPath = FileServer.getFileServer().getBaseDir() + "\\responseFile.txt";

// Get HTTP Status Code
def codeAsString = ctx.getPreviousResult().getResponseCode();
def codeAsInt = codeAsString.toInteger();

if (codeAsInt>=400){
// Get the body from the response:
def body = prev.getResponseDataAsString();

// Create the response file:
def responseFile = new File(inputPath);

// Get the thread name:
def sample = prev.getThreadName();

// Get the sample label
def label = prev.getSampleLabel();

// Get response time and convert epoch to datetime
def endtime = prev.getEndTime();
def epoch = Calendar.getInstance(TimeZone.getTimeZone('GMT'));
epoch.setTimeInMillis(endtime);
def enddate = epoch.format("dd-MMM-yyyy HH:mm:ss zzz");

// Write to file
responseFile << "\n" + "***** Thread Group = " + sample + "\n" + "***** Sample Label = " + label + "\n" + "***** HTTP Status Code = " + codeAsInt + "\n" + "***** End Date = " + enddate + "\n" + "***** Message = " + body + "\n" + "\n";
}

Sample output returned

***** Thread Group = Dummy 1-70
***** Sample Label = Dummy Invalid Id
***** HTTP Status Code = 404
***** End Date = 24-Feb-2020 08:33:46 GMT
***** Message = {"timestamp":"2020-02-24T08:33:46.064+0000","status":404,"error":"Not Found","message":"No message available","path":"/dummy/order-history"}

FURTHER READING

Writing JMeter Functions in Groovy