JMeter Write Full Response Messages to File
Learn how to extract and log detailed HTTP response data from Apache JMeter using Groovy scripting within a JSR223 sampler.
Mark
Performance Testing Expert
When you require a deeper level of logging from Apache JMeter you can use the Groovy programming language and a JSR223 sampler to extract the required values from variables.
Technical Approach
The provided Groovy script captures HTTP responses with status codes 400 and above, extracting:
- HTTP status codes
- Response body content
- Thread names
- Sample labels
- Response timestamps (converted to readable datetime format)
Sample Implementation
import org.apache.jmeter.services.FileServer
// Only log responses with status code 400 or above
if (prev.getResponseCode().toInteger() >= 400) {
def responseCode = prev.getResponseCode()
def responseMessage = prev.getResponseMessage()
def responseData = prev.getResponseDataAsString()
def threadName = prev.getThreadName()
def sampleLabel = prev.getSampleLabel()
def timeStamp = prev.getTimeStamp()
// Convert timestamp to readable format
def dateTime = new Date(timeStamp).format("yyyy-MM-dd HH:mm:ss")
// Get the file path
def testPlanDir = FileServer.getFileServer().getBaseDir()
def outputFile = new File(testPlanDir + "/error_responses.txt")
// Write to file
outputFile.append("=" * 80 + "\n")
outputFile.append("Thread: ${threadName}\n")
outputFile.append("Sample: ${sampleLabel}\n")
outputFile.append("Time: ${dateTime}\n")
outputFile.append("Status: ${responseCode} - ${responseMessage}\n")
outputFile.append("-" * 40 + "\n")
outputFile.append("Response:\n${responseData}\n")
outputFile.append("=" * 80 + "\n\n")
}
Important Caveat
Writing data to files can limit the throughput of your test. Where you intend to push through high workloads, this level of logging may become obstructive.
Consider the following when using file-based logging:
- Use it primarily for debugging and low-volume tests
- Disable or remove the logging for high-throughput performance tests
- Filter carefully to only log errors or specific conditions
- Consider using backend listeners for production-level monitoring
Usage
- Add a JSR223 PostProcessor to your HTTP Request sampler
- Select “groovy” as the scripting language
- Paste the script into the Script panel
- Run your test
The script will create an error_responses.txt file in your test plan directory containing detailed information about failed requests.
Further Reading
Tags: