Using Groovy in JMeter to Log and Save Request/Response Data
This guide demonstrates how to add a JSR223 PostProcessor with Groovy in Apache JMeter to capture slow requests, write request parameters and responses to a log file, and control pagination for automated performance testing, providing complete script examples and console output.
Previously, several articles introduced using Groovy in JMeter for assertions, variables, command execution, and request parameters. This article extends the discussion by showing how to perform file operations with Groovy inside a JMeter test plan, enabling automatic logging of timeout requests and their responses.
Setup
Create a simple Thread Group and a basic HTTP Request.
Add a JSR223 PostProcessor to the request.
Groovy Script
def file = new File("fan.log")
if (!file.exists()) file.createNewFile()
log.info("Working directory:" + file.getAbsoluteFile())
def end_time = prev.getEndTime()
def start_time = prev.getStartTime()
def response = prev.getResponseDataAsString()
if (end_time - start_time > 100) {
file << "FunTester${System.currentTimeMillis()} 参数${sampler.getArguments()} 响应${response}
"
log.info("Response time ${end_time - start_time}")
}
file.eachLine {
log.info("File content: ${it}")
}Console Output Example
2020-03-06 20:08:52,898 INFO o.a.j.e.StandardJMeterEngine: Running the test!
2020-03-06 20:08:52,898 INFO o.a.j.s.SampleEvent: List of sample_variables: []
... (truncated for brevity) ...
2020-03-06 20:08:53,410 INFO o.a.j.a.J.JSR223 文件处理: 工作目录地址:/Users/fv/Applications/apache-jmeter-5.12/bin/fan.log
2020-03-06 20:08:53,410 INFO o.a.j.a.J.JSR223 文件处理: 响应时间356
2020-03-06 20:08:53,410 INFO o.a.j.a.J.JSR223 文件处理: 文件内容:FunTester1583495038269 响应{"success":1,"gt":"3c73c021ac3bfea7b5df8d461b5573c5","challenge":"90c62da9d345de77d32964fe1be7585f","new_captcha":true}
... (additional log entries) ...The script creates or opens fan.log", records the absolute path, measures each sample's execution time, and writes entries only when the response time exceeds 100 ms. It also logs each line of the file for verification.
By adjusting parameters such as pageSize or incrementing page, testers can control pagination and stop when no more content is returned, then restart from page=1. This approach helps trace bugs, capture specific error responses, and manage long‑running queries during performance testing.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
