How to write Locust result of test api to file

UPDATE

Saving csv file with the option --csv is added with this release . So you can run the following command to save result of the test as foo_requests.csv and foo_distribution.csv

locust -f locustfile.py --host=http://localhost --no-web  --hatch-rate=20 --clients=10000 --only-summary --csv=foo

FOR the version below 0.8

There has been a commit for saving the result of Locust but it is not merged to Locust yet. However you can update it manually with this commit. It is adding a new parameters as --statsfile=result.log to save the result.

Then the complete command should look like this

locust -f locustfile.py --host=http://localhost --no-web  --hatch-rate=20 --clients=10000 --only-summary --statsfile=result.log

You can check this post for updating Locust and checking the result of the log.


Another option until the statsfile option is live would be to redirect stderr to an output file, which apparently is where the stats are logged to:

 locust -f locustfile.py --host=http://example.com --no-web --clients=20  --hatch-rate=20 --num-request=1000  --only-summary  > locust.log   2>&1

I have tried to print locust stats in a file without success, but you can do it in using event hook : http://docs.locust.io/en/latest/api.html#available-hooks.

You can add a function to the event request_success and request_failure, so each time a request success or fail your hook function will be called in order to get request data into a list or any variable you want.

Then you can easily print the data into a csv file for instance

Hope it would help you

import locust.events
from locust import HttpLocust, TaskSet


class LocustUser(HttpLocust):
    task_set = TaskSet
    min_wait = 1000
    max_wait = 1000

    request_success_stats = [list()]
    request_fail_stats = [list()]

    def __init__(self):
        locust.events.request_success += self.hook_request_success
        locust.events.request_failure += self.hook_request_fail
        locust.events.quitting += self.hook_locust_quit

    def hook_request_success(self, request_type, name, response_time, response_length):
        self.request_success_stats.append([name, request_type, response_time])

    def hook_request_fail(self, request_type, name, response_time, exception):
        self.request_fail_stats.append([name, request_type, response_time, exception])

    def hook_locust_quit(self):
        self.save_success_stats()

    def save_success_stats(self):
        import csv
        with open('success_req_stats.csv', 'wb') as csv_file:
            writer = csv.writer(csv_file)
            for value in self.request_success_stats:
                writer.writerow(value)