Skip to content

Commit

Permalink
Log unhandled exceptions thrown in User.on_start (#2442)
Browse files Browse the repository at this point in the history
Log unhandled exceptions thrown in User.on_start (instead of just relying on default console logging of unhandled exceptions)
  • Loading branch information
cyberw authored Nov 1, 2023
1 parent 0427175 commit 68ffae8
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
30 changes: 30 additions & 0 deletions locust/test/test_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,33 @@ def my_task(self):
f"{socket.gethostname()}/INFO/root: custom log message",
log_content,
)

def test_user_broken_on_start(self):
with temporary_file(
textwrap.dedent(
"""
from locust import HttpUser, task
class TestUser(HttpUser):
host = "invalidhost"
def on_start(self):
self.client.get("/")
"""
)
) as file_path:
output = subprocess.check_output(
[
"locust",
"-f",
file_path,
"-t",
"1",
"--headless",
],
stderr=subprocess.STDOUT,
timeout=10,
text=True,
)

self.assertIn("ERROR/locust.user.users: Invalid URL", output)
12 changes: 11 additions & 1 deletion locust/user/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
from gevent import GreenletExit, greenlet
from gevent.pool import Group
from urllib3 import PoolManager
import logging
import traceback

logger = logging.getLogger(__name__)
from locust.clients import HttpSession
from locust.exception import LocustError, StopUser
from locust.user.wait_time import constant
Expand All @@ -20,6 +23,8 @@
get_tasks_from_base_classes,
)

logger = logging.getLogger(__name__)


class UserMeta(type):
"""
Expand Down Expand Up @@ -140,7 +145,12 @@ def run(self):
self._taskset_instance = DefaultTaskSet(self)
try:
# run the TaskSet on_start method, if it has one
self.on_start()
try:
self.on_start()
except Exception as e:
# unhandled exceptions inside tasks are logged in TaskSet.run, but since we're not yet there...
logger.error("%s\n%s", e, traceback.format_exc())
raise

self._taskset_instance.run()
except (GreenletExit, StopUser):
Expand Down

0 comments on commit 68ffae8

Please sign in to comment.