2

I am using below code to write user token to a file in Beanshell Post Proccessor. Below code work fine with no issues. But when we execute the script from master -> 3 slaves(3 Slaves execute JMX file in parallel)

Few empty lines and some truncated tokens are written to the file. Appreciate if any one help on this. We need to have actual tokens written to the file with out any truncations and empty lines

import java.io.File;
import org.apache.jmeter.services.FileServer;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.Writer;

File file = new File("/tmp/token.csv");
FileWriter fstream = new FileWriter(file, true);

BufferedWriter out = new BufferedWriter(fstream);

String accesstoken = vars.get("UserTOKEN");
out.write(accesstoken);
out.write("\n");

out.close();
fstream.close();
Kumar
  • 399
  • 4
  • 16
  • please check the answer in the discussion, https://stackoverflow.com/questions/65732172/jmeter-extract-id-variables-from-json-response-and-save-it-in-csv-file-and-us – Jyoti Prakash Mallick Mar 12 '21 at 05:27

2 Answers2

2

${__StringToFile(,,,)} the inbuilt jmeter function is thread safe. I had the same issue while writing to file with more than 1 thread in a thread group. With this function, the issue got resolved.

I used it in JSR223 PostProcessor

Rahul Jadhav
  • 413
  • 3
  • 9
  • 1
    Hi Rahul, thank for above solution. it is working without any issue. but it is writing the variable name in the file followed by value. is there any way to skip variable name and write only variable value – Kumar Mar 14 '21 at 11:04
  • you can add a if statement in your jsr223 component. Pseudo code as below `if(vars.get("variable_name") != null){ ${__StringToFile(filename.csv,${variable_name},,)} }` – Rahul Jadhav Mar 15 '21 at 05:06
1

You're suffering from a race condition, when multiple threads are concurrently writing into the same file it may (and will) result in data corruption and/or loss

So if you want to do this programmatically you need to put the code under the Critical Section Controller so it will be executed only by one thread at a time. However this approach may act like a bottleneck for your test.

A better solution would be using Sample Variables property, if you add the next line to user.properties file:

sample_variables=UserTOKEN

next time you start JMeter the value of the ${UserTOKEN} variable will be written into the .jtl results file (as a separate last column)

If you want to store the value into a separate file - you can go for the Flexible File Writer

Dmitri T
  • 159,985
  • 5
  • 83
  • 133