Search code examples
jmeterfilewriterbeanshell

Jmeter and Filewriter - adding a date + timestamp to the filename


I have created a jmeter that places an order on my site and records the order status and confirmation number. Once the order is booked, I use a BeanShell PostProcessor to print out the extracted variables to a file. I would really like to be able to add a date to the filename, but I have not been able to find a way to do it.

This is what my Bean Shell Post Processor looks like:

FileWriter fstream = new FileWriter("C:\\JMeter\\Results\\log.csv",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(vars.get("scriptName"));
out.write(System.getProperty("line.separator"));
out.write("STATUS: " + vars.get("status"));
out.write(System.getProperty("line.separator"));
out.write("Confirmation Number: " + vars.get("ConfirmationNumber"));
out.write(System.getProperty("line.separator"));
out.write("");
out.write(System.getProperty("line.separator"));
out.write("");
out.close();
fstream.close();

I have tried inserting variables into the filename, but I suspect I have been doing it wrong, because no files are even being created.

Full disclaimer (which may not be necessary given my sample code above): I am not a code person, so please excuse the shoddy code.

Thanks in advance.


Solution

  • You can set a property at the beginning which you can append to your filename later.

    ${__P(UNIQUEID,${__time(YMDHMS)})}
    

    Then you can change your line to the following

        FileWriter fstream = new FileWriter(vars.get("CWD") + "/JMeter/results/log${UNIQUEID}.csv", true);
    

    In the above code, CWD is another variable that I set at the beginning which points to current directory from which Jmeter islaunched.

    import org.apache.jmeter.services.FileServer; 
    
    String sCWd = new String(FileServer.getFileServer().getBaseDir());
    log.info("CWDString=" + sCWd.replace("\\", "/"));
    vars.put("CWD", sCWd.replace("\\\\", "/"));